1

您好我正在尝试将数组存储到 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
4

1 回答 1

2

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

实际上,我认为它不会在第一次调用此方法时崩溃,因为recentPhoto尚未存储在用户默认值中。但在那之后,它会的。

于 2012-08-05T23:09:06.237 回答