标签:
//对于数据的存储: //当需要存储的数据是自定义类的对象时,不管是放在NSArray或者NSDcitionary中,自定义类使用NSUserDefaults存储时,都要 //继承NSCoding协议 //SearchArticleModel.h文件 @interface SearchArticleModel : NSObject<NSCoding>{ @property (nonatomic, assign) NSInteger top; } //SearchArticleModel.m文件 @implementation SearchArticleModel - (id)initWithCoder:(NSCoder *)aDecoder{ self = [super init]; if (self) { self.top = [[aDecoder decodeObjectForKey:@"top"] integerValue]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder{ [aCoder encodeObject:[NSString stringWithFormat:@"%ld",(long)self.top] forKey:@"top"]; } @end //归档和解档的实现方法 //加载最新数据后归档 //articleArr中存储数组 - (void)archiveObject{ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSMutableArray *articleArchiveArr = [[NSMutableArray alloc] init]; for (SearchArticleModel *recommendedAM in articleArr) { ,数组中为 NSData *recommendedObj = [NSKeyedArchiver archivedDataWithRootObject:recommendedAM]; [articleArchiveArr addObject:recommendedObj]; } [defaults setObject:articleArchiveArr forKey:@"articleArr"]; [defaults synchronize]; } //加载界面后解档 //数据放在articleArr数组中 - (void)unarchiveObject{ NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults]; NSMutableArray *recommendArticleModelArr = [[NSMutableArray alloc] init]; for (NSData *data in [defaults objectForKey:@"articleArr"]) { SearchArticleModel *recommendArticleModel = [[SearchArticleModel alloc] init]; recommendArticleModel = [NSKeyedUnarchiver unarchiveObjectWithData:data]; [articleArr addObject:recommendArticleModel]; } }
标签:
原文地址:http://my.oschina.net/u/1782374/blog/506422