[IOS]NSUserDefaults读取和写入
NSUserDefaults可以存取一些短小的信息。
网站建设哪家好,找创新互联!专注于网页设计、网站建设、微信开发、重庆小程序开发公司、集团企业网站建设等服务项目。为回馈新老客户创新互联还提供了大英免费建站欢迎大家使用!
比如存入再读出一个字符串到NSUserDefaults:
- NSString *string = [NSString stringWithString @"hahaha"];
- NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
- [ud setObject:string forKey:@"myKey"];
- NSString *value;
- value = [ud objectForKey:"myKey"];
但是并不是所有的东西都能往里放的。NSUserDefaults只支持: NSString, NSNumber, NSDate, NSArray, NSDictionary.
如果把一个自定义的类存到一个NSArray里,然后再存到NSUserDefaults里也是不能成功的。不信可以试试,如果你成功的请告诉我。
那怎么办呢?
我找到的方法是,让这个自定义类实现
粘代码:
假设有这样一个简单的类对象
- @interface BusinessCard : NSObject
{ - 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
然后再存取时通过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] ;
以上的代码时由另一个程序中截取的,没有测试过,但意思就是这样了。
如果一个自定义类中由另一个自定义类对象,那么所有嵌套的类都要实现
网页名称:[IOS]NSUserDefaults读取和写入
网站网址:http://ybzwz.com/article/ghsies.html