Hi I want to save and retrieve NSObject
class using NSUserDefaults
for that I wrote below code but I am getting exception like below
You can set object like this:
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:savingbean];
[currentDefaults setObject:data forKey:@"DATA"];
[currentDefaults synchronize];
and for get object like this:
NSData *data = [currentDefaults objectForKey:@"DATA"];
SavingBean *token = [NSKeyedUnarchiver unarchiveObjectWithData:data];
For Custom class you have to edit this methods in you bean class:
- (void)encodeWithCoder:(NSCoder *)encoder
{
[encoder encodeObject:self.userName==nil?@"":self.userName forKey: @"userName"];
[encoder encodeObject:self.passWord==nil?@"":self.passWord forKey: @"passWord"];
}
-(id)initWithCoder:(NSCoder *)decoder
{
self = [super init];
if(self)
{
self.userName = [decoder decodeObjectForKey: @"userName"];
self.passWord = [decoder decodeObjectForKey: @"passWord"];
}
return self;
}
Here is most voted similar answer. You can also get good stuff from there.
You can also use JSON Accelerator to create bean class. This is very simple and powerful tool.