我在从NSDictionary读取值时遇到问题。这是我的设置:
NSArray *data = [[NSUserDefaults standardUserDefaults] objectForKey:kMyConstant];
for(id value in data)
{
NSString *stringValue = [value stringForKey:kMyValueConstant]; // This is where the error is
}
然而,当它到达注释行时,我收到以下错误:
2011-12-19 13:54:45.466 MyApp[12587:f803] -[__NSCFDictionary stringForKey:]: unrecognized selector sent to instance 0x6898f70
2011-12-19 13:54:45.468 MyApp[12587:f803] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[__NSCFDictionary stringForKey:]: unrecognized selector sent to instance 0x6898f70'
我真的不明白问题出在哪里。这是我用来设置NSUserDefaults的代码:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
// Create the NSDictionary to hold all of the data
NSMutableDictionary *appDefaults = [NSMutableDictionary dictionary];
// Create a couple of samples
NSMutableDictionary *sampleOne = [NSMutableDictionary dictionary];
[sampleOne setValue:@"Value A" forKey:kMyValueConstant];
NSMutableDictionary *sampleTwo = [NSMutableDictionary dictionary];
[sampleTwo setValue:@"Value B" forKey:kMyValueConstant];
NSMutableArray *list = [[NSMutableArray alloc] initWithObjects:sampleOne, sampleTwo, nil];
[appDefaults setValue:list forKey:kMyConstant];
[defaults registerDefaults:appDefaults];
[defaults synchronize];
答案 0 :(得分:3)
如果value
为NSDicitonary
类型,则应使用此代码:
NSString *stringValue = [[value objectForKey:kMyValueConstant] stringValue];
答案 1 :(得分:2)
只需替换
NSString *stringValue = [value stringForKey:kMyValueConstant];
带
NSString *stringValue = [value objectForKey:kMyValueConstant];