利用NSUserdefaults来存储自定义的NSObject类及自定义类数组
1.利用NSUserdefaults来存储自定义的NSObject类
利用NSUserdefaults也可以来存储及获取自定义非框架类对象,不过自定义的NSObject类需要实现NSCoding协议(包含2个必须实现的方法)。存储过程是将自定义的NSObject转换成NSData存储。
存储:
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:object];
[[NSUserDefaults standardUserDefaults] setObject:data forKey:thekey];
[[NSUserDefaults standardUserDefaults] synchronize];
获取:
NSData *ldta = [[NSUserDefaults standardUserDefaults] objectForKey:thekey];
object = [NSKeyedUnarchiver unarchiveObjectWithData:data];
2.利用NSUserdefaults来存储自定义对象的数组
2.1 归档数组中存储的自定义类必须实现NSCoding协议
//WZToDoItem.h文件
#import <Foundation/Foundation.h>
@interface WZToDoItem : NSObject<NSCoding>
@property (copy,nonatomic) NSString *text;
@end //WZToDoItem.m文件
#import "WZToDoItem.h"
@implementation WZToDoItem
//NSCoding协议必须实现方法1
- (void)encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeObject:self.text forKey:@"TEXT"];
}
//NSCoding协议必须实现方法2
- (instancetype)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.text = [aDecoder decodeObjectForKey:@"TEXT"];
}
return self;
}
@end
2.2 将包含自定义WZToDoItem对象的数组转换成NSData来存储
- (void)viewDidLoad { //创建自定义对象的数组arrayM
NSMutableArray *arrayM = [NSMutableArray array];//可变数组初始化才能用
for (int i = ; i < arr.count; i++) {
WZToDoItem *toDoItem = [[WZToDoItem alloc]init];
toDoItem.text = [NSString stringWithFormat:@"这是第%d个代办事项",i];
[arrayM addObject:toDoItem];
}
//存储
NSUserDefaults *userDfs = [NSUserDefaults standardUserDefaults];
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayM];
[userDfs setObject:data forKey:@"toDoItems"];
[userDfs synchronize]; //获取
NSData *data = [[NSUserDefaults standardUserDefaults] dataForKey:@"toDoItems"];
NSArray *array = [NSKeyedUnarchiver unarchiveObjectWithData:data]; }