0

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
2
  • 1
    Why are you using arrayForKey? You need to retrieve the data and unarchive it Commented Sep 25, 2017 at 23:22
  • I am not sure but you are logging the same object even then it is showing you NULL? Commented Sep 25, 2017 at 23:45

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

You have to unarchive your data first at the time of retrieving back. You are directly accessing the data. This won't work. You can do it the similar way you are archiving the data

NSData *dataObj = [currentDefaults objectForKey:@"myItems"];

Items *myRetrievedItems = [NSKeyedUnarchiver unarchiveObjectWithData:dataObj];

For more reference, you can consider this answer.

Hope this helps. Thanks!

2 Comments

Got [Items initWithCoder:]: unrecognized selector sent to instance
@user6631314 as mention by iGenio, it might be because your class does not conform to NSCoding protocol. You can do it like this: stackoverflow.com/a/6696735/3824808
0

Your access value method is wrong.

You can get the array in following code:

Items *myRetrievedItems = [[[NSUserDefaults standardUserDefaults] objectForKey:@"myItems"] mutableCopy];

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.