Write yer class like this:
@interface Person: NSObject <NSCoding> {
NSString *name;
float *height; //Note height is a pointer, presumabaly due to a dependancy in code we dont control
NSUInteger age;
}
@property (nonatomic, retain) NSString *name;
@property (readwrite) height;
@property (readwrite) age;
@end
@implementation Person
@synthesize name;
@synthesize height;
@synthesize age;
#define PersonNameKey @"PersonNameKey"
#define PersonHeightKey @"PersonHeightKey"
#define PersonAgeKey @"PersonAgeKey"
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if(self) {
self.name = [decoder decodeObjectForKey:PersonNameKey];
//height is a pointer to we need to do this
&self.height = [decoder decodeFloatForKey:PersonHeightKey];
self.age = [decoder decodeIntForKey:PersonAgeKey];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:PersonNameKey];
//dereferance the pointer to persist the value
[encoder encodeFloat:*self.height forKey:PersonHeightKey]
[encoder encodeInt:self.age forKey:PersonAgeKey];
}
- (void)dealloc {
self.name = nil;
[super dealloc];
}
@end
Then you can do a:
Person = [Person alloc] init];
person.name = @"name";
person.age = 10;
person.height = 1.6;
[NSUserDefaults standardUSerDefaults] setObject:person forKey:@"SomeKey"];
Person *newPerson = [[NSUserDefaults standardUSerDefaults] objectForKey:@"SomeKey"];
If you wanted to persist a collection of the objects you are in luck because NSArray is NSCoding Compliant. All you need to do is:
NSArray *arrayOfPersons = [person1, person2, person3, nil];
[NSUSerDefaults standardUSerDefaults] setObject:arrayOfPersons forKey@"SomeKey"];
Note: Ususaly before posting on SO I dbl check my code in a complier, but I'm reinstalling today so there may be typos.