Sunday 24 November 2013

Save and Retrieve Custom Object from NSUserDefaults


If you have a custom class and save the object of class in NSUserDefaults you have the use initWithCoder and encodeWithCoder.

Example class :-

TestClass.h

 #import <Foundation/Foundation.h>  
   
 @interface TestClass : NSObject{  
   NSString *strTest;  
   NSMutableDictionary *dictTest;  
   int test;  
 }  
 @property(nonatomic,retain)NSString *strTest;  
 @property(nonatomic,retain)NSMutableDictionary *dictTest;  
 @property(nonatomic,assign)int test;  
   
 @end  

TestClass.m

 #import "TestClass.h"  
   
 @implementation TestClass  
   
 @synthesize strTest,dictTest,test;  
   
 -(id)initWithCoder:(NSCoder *)coder{  
   self=[[TestClass alloc]init];  
   if (self!=nil) {  
     self.strTest=[coder decodeObjectForKey:@"strTest"];  
     self.dictTest=[coder decodeObjectForKey:@"dictTest"];  
     self.test=[coder decodeIntegerForKey:@"test"];  
   }  
   return self;  
 }  
   
 -(void)encodeWithCoder:(NSCoder *)coder{  
   [coder encodeObject:self.strTest forKey:@"strTest"];  
   [coder encodeObject:self.strTest forKey:@"dictTest"];  
   [coder encodeInt:self.test forKey:@"test"];  
 }  
   
 @end  


Save and retrieve this TestClass object from NSUserDefaults.

Save Object

//create object

 TestClass *objTest=[[TestClass alloc]init];  

//set data

 objTest.strTest=@"Testing";  
 objTest.test=10;  
 NSMutableDictionary *dict=[[NSMutableDictionary alloc]init];  
 [dict setObject:@"Testing" forKey:@"Test"];  
 objTest.dictTest=dict;  

//save object to NSUserDefaults

 NSData *data=[NSKeyedArchiver archivedDataWithRootObject:objTest];  
 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  
 [userDefaults setObject:data forKey:@"customObject"];  
 [userDefaults synchronize];  

Retrieve Object

 NSUserDefaults *userDefaults=[NSUserDefaults standardUserDefaults];  
 NSData *dataSavedForObject = [userDefaults objectForKey:@"customObject"];  
 TestClass *objTest=[NSKeyedUnarchiver unarchiveObjectWithData:dataSavedForObject];  

Now you get the object of TestClass.


No comments:

Post a Comment