Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27133

Save NSArray to NSUserDefaults issues (using custom object in array)

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.

Upvotes: 2

Views: 1745

Answers (2)

Rob Napier
Rob Napier

Reputation: 299345

Everything put into NSUserDefaults must be a valid property list object (NSData, NSString, NSNumber, NSDate, NSArray, or NSDictionary). 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 to NSData.

Serializing to NSData is handled with NSKeyedArchiver. See Storing NSColor in User Defaults for the canonical example of this. (That document is very old and still references NSArchiver which will work fine for this problem, but NSKeyedArchiver is now the preferred serializer.)

In order to archive using NSKeyedArchiver, your object must conform to NSCoding as noted by @harakiri.

Upvotes: 2

cweinberger
cweinberger

Reputation: 3588

You need to conform to the <NSCoding> protocol and implement -initWithCoder: and -encodeWithCoder: in your custom object.

See: https://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Protocols/NSCoding_Protocol/Reference/Reference.html

Upvotes: 2

Related Questions