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);
ModelClas:-
.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;
@end
.m file:-
#import "SavingBean.h"
@implementation SavingBean
@synthesize userName,passWord;
-(void)savingData :(NSString*)username :(NSString*)password{
userName = username;
passWord = password;
}
@end
You can set object like this:
and for get object like this:
For Custom class you have to edit this methods in you bean class:
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.
From good answer of Jayesh Thanki I tried sample from this question.I followed your coding.First I tried Save and Retrieve directly without encoder and decoder method.
For Save
For Retrieve
Now it shows error
Then I googled most of the answer say
encodeWithCoder
initWithCoder
Then I understood that we must implement the encodeWithCoder and inintWithCoder first in NSObject Class.After that only we should save and retrieve the data.
Now First we have to implement the encodeWithCoder and initWithCoder in SavingBean.m
Then in ViewController.m
For Save
For Retrieve
Now when I run the application it does not show any error.It works fine now.
Why I give these things here is If anybody sees and tries this answer in some case they can get the error like above.So if they prefer two answer for this question they can very easily understand and get the solution very simply.
encodeWithCoder and initWithCoder of NSCoding