I try to save my object to NSUserDefaults. But when I call this method again it is not have any info about previous operation.
There is my method below:
- (void)addToCart {
if([[NSUserDefaults standardUserDefaults] objectForKey:kCart]) {
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
NSMutableArray *products = [[NSMutableArray alloc] initWithArray:[prefs objectForKey:kCart]];
[products addObject:self.product];
[prefs setObject:products forKey:kCart];
[prefs synchronize];
[products release];
}
else {
//Saving...
NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
[prefs setObject:[NSArray arrayWithObjects:self.product, nil] forKey:kCart];
[prefs synchronize];
}
}
I need to save a collection with a products to NSUserDefault. I wrap my object to NSArray and save it but it doesn’t work.
Everything put into
NSUserDefaultsmust be a valid property list object (NSData,NSString,NSNumber,NSDate,NSArray, orNSDictionary). All collection elements must themselves also be property list objects.In order to save non-PL objects into
NSUserDefaults, you must first convert the object into a PL object. The most generic way to do this is by serializing it toNSData.Serializing to
NSDatais handled withNSKeyedArchiver. See Storing NSColor in User Defaults for the canonical example of this. (That document is very old and still referencesNSArchiverwhich will work fine for this problem, butNSKeyedArchiveris now the preferred serializer.)In order to archive using
NSKeyedArchiver, your object must conform toNSCodingas noted by @harakiri.