2012-08-05 96 views
1

嗨我想存儲一個數組到NSUserDefaults但我有麻煩。該方法接受一個NSDictionary,我將其存儲到一個數組中,該數組將存儲到NSUSerDefaults中。問題是當我做一個mutableCopy它說它是一個字典,而不是類型NSMutable數組?這個方法是我第一次調用NSUserDefaults,所以我不確定錯誤發生的原因是什麼?下面是代碼感謝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 

回答

2

我相信問題是,在這個方法的最後,你嘗試存儲recentPhoto,這是一本字典,爲用戶默認而不是recentPhotos,您想要存儲的可變數組。

實際上,我認爲在第一次調用此方法時不會崩潰,因爲recentPhoto尚未以用戶默認值存儲。但之後,它會。

+0

但是當我執行第一個NSLog時,該方法崩潰 – 2012-08-05 23:09:57

+1

是的,它沒有objectAtIndex:方法,因爲您從用戶獲得的默認值是字典,而不是數組。 – Selkie 2012-08-05 23:17:57

+0

當我想知道我使用的某些應用程序的背後是什麼代碼時,就像這樣的時代... – jrtc27 2012-08-05 23:27:53

相關問題