码迷,mamicode.com
首页 > 其他好文 > 详细

NSUserDefaults读取和写入自定义对象

时间:2016-11-16 11:40:48      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:dealloc   atom   lin   imp   src   start   elf   int   pen   

NSUserDefaults可以存取一些短小的信息。

比如存入再读出一个字符串到NSUserDefaults:

技术分享
- NSString *string = [NSString stringWithString @"hahaha"];
- NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
- [ud setObject:string forKey:@"myKey"];
- NSString *value;
- value = [ud objectForKey:"myKey"];
View Code

但是并不是所有的东西都能往里放的。NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.

 

如果把一个自定义的类存到一个NSArray里,然后再存到NSUserDefaults里也是不能成功的。不信可以试试,如果你成功的请告诉我。

那怎么办呢?

 

我找到的方法是,让这个自定义类实现<NSCoding>协议中的- (id) initWithCoder: (NSCoder *)coder方法和- (void) encodeWithCoder: (NSCoder *)coder方法(obj-c的协议protocol就是java的接口interface,就是C++的纯虚函数),然后把该自定义的类对象编码到NSData中,再从NSUserDefaults中进行读取。

 

粘代码:

假设有这样一个简单的类对象

技术分享
- @interface BusinessCard : NSObject <NSCoding>{
-     NSString *_firstName;
-     NSString *_lastName;
- }
- @property (nonatomic, retain) NSString *_firstName;
- @property (nonatomic, retain) NSString *_lastName;
- @end;
-
- @implementation BusinessCard
- @synthesize _firstName, _lastName;
- - (void)dealloc{
-     [_firstName release];
-     [_lastName release];
-     [super dealloc];
- }
- - (id) initWithCoder: (NSCoder *)coder
- {
-     if (self = [super init])
-     {
-         self._firstName = [coder decodeObjectForKey:@"_firstName"];
-         self._lastName = [coder decodeObjectForKey:@"_lastName"];
-     }
-     return self;
- }
- - (void) encodeWithCoder: (NSCoder *)coder
- {
-     [coder encodeObject:_firstName forKey:@"_firstName"];
-     [coder encodeObject:_lastName forKey:@"_lastName"];
-
- }
-
- @end
View Code1

然后再存取时通过NSData做载体:

技术分享
BusinessCard *bc = [[BusinessCard alloc] init];
NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
NSData *udObject = [NSKeyedArchiver archivedDataWithRootObject:bc];
[ud setObject:udObject forKey:@"myBusinessCard"];
[bc release];
udObject = nil;
udObject = [ud objectForKey:@"myBusinessCard"];
bc = [NSKeyedUnarchiver unarchiveObjectWithData:udObject] ;
View Code

 

NSUserDefaults读取和写入自定义对象

标签:dealloc   atom   lin   imp   src   start   elf   int   pen   

原文地址:http://www.cnblogs.com/IT-jqm/p/NSUserDefaults.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!