无法从NSDictionary(iPhone)加载值

时间:2011-12-19 14:06:45

标签: iphone objective-c nsdictionary nsuserdefaults

我在从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];

2 个答案:

答案 0 :(得分:3)

如果valueNSDicitonary类型,则应使用此代码:

NSString *stringValue = [[value objectForKey:kMyValueConstant] stringValue];

答案 1 :(得分:2)

只需替换

NSString *stringValue = [value stringForKey:kMyValueConstant]; 

NSString *stringValue = [value objectForKey:kMyValueConstant];