views:

60

answers:

2

Hello,

I am having a... strange problem.

I am adding an NSDictionary to an NSArray, then saving it to the defaults. When I check the object count of that key on the user defaults, it says the count is 0, but the array that's "on memory" has that object (so the count is 1).

The code, along with the output it gives is this:

(array is an NSArray, defaults is [NSUserDefaults standardUserDefaults])

- (void)addSongToQueue:(NSDictionary *)songData {
 [array addObject:songData];
 [defaults setObject:array forKey:@"OfflineArray"];
 [defaults synchronize];

#if DEBUG
 NSLog(@"Dictionary Data Received: %@", songData);
 NSLog(@"Object Count on Array: %u", [array count]);
 NSLog(@"Object Count on Defaults: %u", [[NSArray arrayWithArray:[defaults objectForKey:@"OfflineArray"]] count]);
 [defaults removeObjectForKey:@"OfflineArray"];
 [defaults synchronize];
#endif
}

This is how I am calling it:

[className addSongToQueue:[NSDictionary dictionaryWithObjectsAndKeys:@"yadda", @"yadda", nil]];

This is the output: (I ran it twice, just to make sure :P)

2010-10-11 21:47:35.807 AppName[1119:207] Dictionary Data Received: {
yadda = yadda;
    }

2010-10-11 21:47:35.807 AppName[1119:207] Object Count on Array: 1
2010-10-11 21:47:35.808 AppName[1119:207] Object Count on Defaults: 0
2010-10-11 21:47:36.647 AppName[1119:207] Dictionary Data Received: {
yadda = yadda;
    }

2010-10-11 21:47:36.647 AppName[1119:207] Object Count on Array: 2
2010-10-11 21:47:36.648 AppName[1119:207] Object Count on Defaults: 0

So yeah. I can't be able to solve it. :/

Thanks in advance. :)

+1  A: 

Are you really just putting NSString instances into the dictionary? Every time I've seen incomplete saving from NSUserDefaults, it's been because some of the objects in the dictionary aren't compatible with the plist format. You can only store NSNumber, NSString, NSArray, NSDictionary, NSData on all versions of the plist format (some allow NSDate too).

Graham Lee
In the real app use I am saving NSStrings and NSNumbers, BUT as you see here, even saving a dictionary with a NSString doesn't work.
MegaEduX
+2  A: 

Are you sure defaults isn't nil?

David Gelhar
Bet this is it. If you try to set an invalid object, you get an exception.
Chuck
That was indeed it, but that happened because the function where I was setting defaults = [NSUserDefaults standardUserDefaults]; wasn't being run for some reason. That being said, answer accepted. Thanks!
MegaEduX