is a microblog
home archives search feed blogroll

Store Custom Objects In NSUserDefaults

Your interface must implement NSCoding.

@interface MyObject : NSObject <NSCoding>

@property (strong, nonatomic) NSString *firstValue;
@property (strong, nonatomic) NSString *secondValue;


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];

You can retrieve it like this.

NSData *data = [[NSUserDefaults standardUserDefaults] valueForKey:@"my_object"];
MyObject *myObj = [NSKeyedUnarchiver unarchiveObjectWithData:data];
Posted on 2018-04-08   #ios     #objc  

← Next post    ยท    Previous post →