NSCoding & NSUserDefaults to store something simple…

Lets say you created an app which lets you select a person from the Address Book and you wish to set that person as the default user to use each time you launch the app. You want to store that preference in NSUserDefaults. If there is a lot of data to that person, you probably don’t want to store each key, key by key…This is where you can modify your NSObject class to conform to NSCoding and quickly save & load your data.

1. In you NSObject Class add theprotocol.

@interface CustomObject : NSObject <NSCoding>

2. Now add these 2 methods to your NSObject Class:

- (void) encodeWithCoder:(NSCoder*)encoder;
- (id) initWithCoder:(NSCoder*)decoder;

3. Now implement the methods

- (void) encodeWithCoder:(NSCoder*)encoder {
    // If parent class also adopts NSCoding, include a call to
    // [super encodeWithCoder:encoder] as the first statement.

    [encoder encodeObject:someArray forKey:@"someArray"];
    [encoder encodeInteger:someInteger forKey:@"someInteger"];
    [encoder encodeBool:someBool forKey:@"someBool"];
}

- (id) initWithCoder:(NSCoder*)decoder {
    if (self = [super init]) {
      // If parent class also adopts NSCoding, replace [super init]
      // with [super initWithCoder:decoder] to properly initialize.

      // NOTE: Decoded objects are auto-released and must be retained
      someArray = [[decoder decodeObjectForKey:@"someArray"] retain];
      someInteger = [decoder decodeIntegerForKey:@"someInteger"];
      someBool = [decoder decodeBoolForKey:@"someBool"];
    }
    return self;
}

4. Finally, archive your object doing this:

CustomObject *object; // Assume this exists
NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
// Now do something with your NSData object, such
// as write it to a file or save it to NSUserDefaults

5. And retrieve it using this code:

NSData *encodedObject;
// First retrieve your NSData object by reading it
// from a file or grabbing it from NSUserDefaults
CustomObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];

6. Now simply use your object where and as needed!

 

Leave a Reply