Search code examples
iosnsarraynsuserdefaults

IOS/Objective-C: Save Custom Array as NSUserDefault


I am trying to save an array of objects into an NSUserDefault without success. When I log out the array before the attempt it is full of object. However, when I try to log out the NSUserDefault it is NULL. Can anyone see what I might be doing wrong? Thanks for any suggestions:

 Items *myItems = [mutableFetchedObjects mutableCopy];
    NSLog(@"my Items%@",myItems);//LOGS OUT LONG LIST OF ITEMS
    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myItems];
    [currentDefaults setObject:data forKey:@"myItems"];
[currentDefaults synchronize];
    Items *myRetrievedItems = [[[NSUserDefaults standardUserDefaults] arrayForKey:@"myItems"] mutableCopy];
    NSLog(@"my Retrieved Items%@",myRetrievedItems); //LOGS OUT AS NULL

Solution

  • As the other answers mentioned, it is because your array is not complying to the NSDictionary types (string, binary, bool, etc). Your members of array is of custom types therefore it cannot be saved. What you need to do is convert your array to binary first and then save it.