NSCoding
.
@interface MyObject : NSObject <NSCoding>
@property (strong, nonatomic) NSString *firstValue;
@property (strong, nonatomic) NSString *secondValue;
@end
Your implementation must include encodeWithCoder
and initWithCoder
- (void)encodeWithCoder:(NSCoder*)encoder {
[encoder encodeObject:self.firstValue forKey:@"first_value"];
[encoder encodeObject:self.secondValue forKey:@"second_value"];
}
- (id)initWithCoder:(NSCoder*)decoder {
self = [MyObject new];
self.firstValue = [decoder decodeObjectForKey:@"first_value"];
self.secondValue = [decoder decodeObjectForKey:@"second_value"];
return self;
}
You can then store MyObject
in NSUserDefaults
like this.
MyObject *myObj = [MyObject new];
myObj.firstValue = @"This is the first value";
myObj.secondValue = @"This is another value";
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:myObj];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:@"my_object"];
[[NSUserDefaults standardUserDefaults] synchronize];