本文介绍了如何在iOS中使用NSUserDafaults保存和检索NSObject类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
您好我想使用 NSUserDefaults
保存并检索 NSObject
类,因为我写了下面的代码,但我得到了例如下面的
Hi I want to save and retrieve NSObject
class using NSUserDefaults
for that I wrote below code but I am getting exception like below
用于保存: -
SavingBean*savingbean = [[SavingBean alloc]init];
[savingbean savingData:userName.text :passWord.text];
NSUserDefaults * defaults = [[NSUserDefaults alloc]init];
[defaults setObject:savingbean forKey:@"DATA"];
用于检索: -
defaults = [[NSUserDefaults alloc]init];
savingbean = [defaults objectForKey:@"DATA"];
NSLog(@"Username is===>%@",savingbean.userName);
NSLog(@"Password is===>%@",savingbean.passWord);
ModelClas: -
.h文件: -
#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文件: -
#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:
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:savingbean];
[currentDefaults setObject:data forKey:@"DATA"];
[currentDefaults synchronize];
和get对象是这样的:
and for get object like this:
NSData *data = [currentDefaults objectForKey:@"DATA"];
SavingBean *token = [NSKeyedUnarchiver unarchiveObjectWithData:data];
对于Custom类,你必须在bean类中编辑这个方法:
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.
你也可以使用来创建bean类。这是一个非常简单而强大的工具。
You can also use JSON Accelerator to create bean class. This is very simple and powerful tool.
这篇关于如何在iOS中使用NSUserDafaults保存和检索NSObject类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!