NSUserDefaults支持的数据类型:NSString,NSNumber(NSInteger、float、double),NSArray,NSDictionary,NSDate,BOOL。
如果需要缓存自定义的数据类型,需要遵循NSCoding协议,然后实现NSCoding的两个协议方法,归档与反归档。
例如我们要保存一个新闻列表的数据 .h文件
@interface newsList : NSObject<NSCoding>
@property (nonatomic,copy)NSString *newsId;
@property (nonatomic,copy)NSString *title;
@property (nonatomic,copy)NSString *contentUrl;
@end
@interface newsListModelData : NSObject<NSCoding>
@property (nonatomic, strong)NSArray *newsList;
@end
@interface newsListModel : BaseModel<NSCoding>
@property (nonatomic, strong)newsListModelData *data;
@end
.m 文件,实现NSCoding的协议方法
@implementation newsList
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.newsId = [aDecoder decodeObjectForKey:@"newsId"];
self.title = [aDecoder decodeObjectForKey:@"title"];
self.contentUrl = [aDecoder decodeObjectForKey:@"contentUrl"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.newsId forKey:@"newsId"];
[aCoder encodeObject:self.title forKey:@"title"];
[aCoder encodeObject:self.contentUrl forKey:@"contentUrl"];
}
@end
@implementation newsListModelData
+(NSDictionary *)mj_objectClassInArray {
return @{@"newsList" : @"newsList"};
}
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.newsList = [aDecoder decodeObjectForKey:@"newsList"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.processUrl forKey:@"processUrl"];
[aCoder encodeObject:self.statementUrl forKey:@"statementUrl"];
[aCoder encodeObject:self.newsList forKey:@"newsList"];
}
@end
@implementation newsListModel
- (id)initWithCoder:(NSCoder *)aDecoder {
if (self = [super init]) {
self.data = [aDecoder decodeObjectForKey:@"data"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder{
[aCoder encodeObject:self.data forKey:@"data"];
}
@end
创建一个类存储数据和读取数据的方法 .h文件
+(void)setNewListModel:(newsListModel *)value;
+(newsListModel *)getNewListModel;
.m文件实现方法
定义一个唯一的宏变量
#define kUserDefaultsNewsListModel @"newsList"
+(void)setNewListModel:(newsListModel *)value {
NSData *myEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:value];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:myEncodedObject forKey:kUserDefaultsNewsListModel];
[[NSUserDefaults standardUserDefaults] synchronize];
}
+(newsListModel *)getNewListModel {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData *myEncodedObject = [defaults objectForKey:kUserDefaultsNewsListModel];
return (newsListModel *)[NSKeyedUnarchiver unarchiveObjectWithData:myEncodedObject];
}
获取到model数据之后进行保存
[NSUserDefaultsTools setNewListModel:companyModel];
读取model数据
newsListModel*model = [EdlNSUserDefaultsTools getNewListModel];
网友评论