【问题标题】:NSUserDefaults and storing valuesNSUserDefaults 和存储值
【发布时间】:2012-08-05 22:47:54
【问题描述】:

您好,我正在尝试将数组存储到 NSUserDefaults 中,但遇到了麻烦。该方法接受一个 NSDictionary,我将其存储到一个数组中,该数组将存储到 NSUSerDefaults 中。问题是当我制作一个 mutableCopy 时,它说它是一个字典而不是 NSMutable 数组类型?这个方法是我第一次调用 NSUserDefaults 所以我不确定为什么会发生错误?这是代码谢谢

+(void) getRecentPhoto:(NSDictionary *)recentPhoto{

NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
 //stores it as a dictionary? error happens here
NSMutableArray* recentPhotos = [[defaults objectForKey:@"recentPhoto"] mutableCopy];
NSLog(@"%@", [recentPhotos class]);
if(!recentPhotos) recentPhotos = [NSMutableArray array];
BOOL copy = NO;

//these will crash the program
NSLog(@"%@", [[recentPhotos objectAtIndex:0] objectForKey:@"id"]);
NSLog(@"%@", [recentPhoto objectForKey:@"id"]);

 //this checks if it has been stored before by using an id key
for(int i =0; i < [recentPhotos count]; i++){

    if ([[[recentPhotos objectAtIndex:i] objectForKey:@"id"] isEqualToString:[recentPhoto objectForKey:@"id"]] ) {
        copy = YES;
    }
}
if(copy ==NO)
[recentPhotos addObject:recentPhoto];
[defaults setObject:recentPhoto forKey:@"recentPhoto"];
[defaults synchronize];


}

这是错误

 NSInvalidArgumentException', reason: '-[__NSCFDictionary objectAtIndex:]: unrecognized selector

【问题讨论】:

    标签: objective-c xcode nsmutablearray nsuserdefaults


    【解决方案1】:

    我相信问题在于,在此方法的最后,您尝试将 recentPhoto(它是一个字典)存储到用户默认值中,而不是要存储的可变数组 recentPhotos

    其实我认为在第一次调用这个方法时它不会崩溃,因为recentPhoto没有被存储在用户默认值中。但在那之后,它会的。

    【讨论】:

    • 但是当我执行第一个 NSLog 时该方法崩溃
    • 是的,它没有 objectAtIndex: 方法,因为您从用户默认获得的是字典,而不是数组。
    • 有时我想知道我使用的某些应用程序背后的代码是什么...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-25
    • 2014-10-14
    • 2015-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多