views:

154

answers:

0

Currently I use NSUserDefaults and I'm interested in using NSUserDefaultsController, so that I get notifications when things change.

Below is my current code.

items = /* NSArray of MYItem's */;
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:items];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:kMYItems];

How should I rework my code to store items in NSUserDefaultsController ? Is NSKeyedArchiver the smartest way to store arrays?


UPDATE: AHA, I think I have found a solution myself. Is it a good solution?

// save items
items = /* NSArray of MYItem's */;
NSData* data = [NSKeyedArchiver archivedDataWithRootObject:items];
[[[NSUserDefaultsController sharedUserDefaultsController] values] setValue:data forKey:kMYItems];

// load items
NSData* data = [[[NSUserDefaultsController sharedUserDefaultsController] values] valueForKey:kMYItems];
NSArray* items = [NSKeyedUnarchiver unarchiveObjectWithData:data];

@interface MYItem : NSObject <NSCoding> {
    NSString* name;
    NSString* path;
}
@property (copy) NSString* name;
@property (copy) NSString* path;
@end

@implementation MYItem
@synthesize name, path;

-(void)encodeWithCoder:(NSCoder*)coder {
    [coder encodeObject:name forKey:@"name"];
    [coder encodeObject:path forKey:@"path"];
}
-(id)initWithCoder:(NSCoder*)coder {
    [super init];
    [self setName:[coder decodeObjectForKey:@"name"]];
    [self setPath:[coder decodeObjectForKey:@"path"]];
    return self;
}
@end