AbhiRam AbhiRam - 3 months ago 11x
iOS Question

How to Save and Retrieve NSObject class using NSUserDafaults in Ios

Hi i want to Save and Retrieve NSObject class using NSUserDefaults for that i wrote below code but i am getting exception like below

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to insert non-property list object for key DATA'

For Saving:-

SavingBean*savingbean = [[SavingBean alloc]init];
[savingbean savingData:userName.text :passWord.text];

NSUserDefaults * defaults = [[NSUserDefaults alloc]init];
[defaults setObject:savingbean forKey:@"DATA"];

For Retrieving:-

defaults = [[NSUserDefaults alloc]init];
savingbean = [defaults objectForKey:@"DATA"];

NSLog(@"Username is===>%@",savingbean.userName);
NSLog(@"Password is===>%@",savingbean.passWord);


.h file:-

#import <Foundation/Foundation.h>

@interface SavingBean : NSObject{

NSString *userName;
NSString *passWord;

@property(nonatomic, retain) NSString *userName;
@property(nonatomic, retain) NSString *passWord;

-(void)savingData :(NSString*)userName :(NSString*)password;


.m file:-

#import "SavingBean.h"

@implementation SavingBean
@synthesize userName,passWord;

-(void)savingData :(NSString*)username :(NSString*)password{

userName = username;
passWord = password;



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