If I have a custom class Person which has three variables (which are propertized and synthesized):
NSString* theName;
float* theHeight;
int theAge;
>
@Brad Smith's answer is not complete, and even is incorrect in some sense. We have to use NSKeyedArchiver and NSKeyedUnarchiver as follows:
Make your class (for example in this case Person) to conform to protocol NSCoding and implement both the methods as:
- (id)initWithCoder:(NSCoder *)decoder {
self = [super init];
if(self) {
self.name = [decoder decodeObjectForKey:];
// as height is a pointer
*self.height = [decoder decodeFloatForKey:];
self.age = [decoder decodeIntForKey:];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)encoder {
[encoder encodeObject:self.name forKey:];
//as height is a pointer
[encoder encodeFloat:*self.height forKey:]
[encoder encodeInt:self.age forKey:];
}
Using NSUserDefaults
// Write to NSUserDefaults
NSData *archivedObject = [NSKeyedArchiver archivedDataWithRootObject:];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:archivedObject forKey:];
[defaults synchronize];
// Read from NSUserDefaults
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *archivedObject = [defaults objectForKey:];
*obj = ( *)[NSKeyedUnarchiver unarchiveObjectWithData:archivedObject];