0

I am doing an iphone game and saving data using NSUserDefaults. Here is how I save a user:

-(void) saveUser:(User*)user forPosition:(int) position{
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:user];
NSUserDefaults*savedData=[NSUserDefaults standardUserDefaults];
[savedData setValue:myEncodedObject forKey:[NSString stringWithFormat:@"user%i",position]];
[savedData synchronize];
self.currentUser=user;}

And here is how I load it:

-(BOOL) loadUser:(int) position{
if([savedData objectForKey:[NSString stringWithFormat:@"user%i",position]]){
    NSData *encodedObject = [savedData objectForKey:[NSString stringWithFormat:@"user%i",position]];
    User *user = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    self.currentUser=user;
    return YES;
}
else return NO;}

As you can see, I am saving a custom class on NSUserDefaults. To do that I used guidance from How to store custom objects in NSUserDefaults (in case anyone is interested).

When I use this in the simulator it works perfectly. The problem is that if I run this on my iphone (iphone 6 on ios 8.1) it doesn't load anything.

Any ideas of what it could be? I've already visited this question NSUserdefaults works on Simulator but not on Device but nothing worked. Thanks!

Community
  • 1
  • 1
  • 1
    You could just print all contents of your NSUserdefaults and check. Maybe also put it in the question here.. Here is how to do it http://stackoverflow.com/questions/1676938/easy-way-to-see-saved-nsuserdefaults#1848980 – Ganesh Somani Apr 07 '15 at 04:06
  • Thanks, by printing the content I found what was wrong and I could fix it. The problem was that the (int) position was receiving a wrong number (I don't know why and I don't know why on the simulator it worked correctly) and therefore it saved the user with another key. I found a way around this problem. Thanks – Matias Grunwaldt Apr 07 '15 at 16:41
  • Just added the same as answer. Maybe you could accept the answer. Thanks – Ganesh Somani Apr 08 '15 at 01:21

2 Answers2

0

Have you tried setObject instead of setValue ?

[savedData setObject:myEncodedObject forKey:[NSString stringWithFormat:@"user%i",position]];
Samir
  • 902
  • 9
  • 23
0

I guess there could be some problem saving it.

Check what exactly is being saved. You can print the complete NSUserDefaults using this

Community
  • 1
  • 1
Ganesh Somani
  • 2,280
  • 2
  • 28
  • 37