标签:
将自定义的类的数据以数组的形式直接存储到NSUserDefaults中会报错,需要进行转换,且需要将该类实现NSCoding协议。
e.g.
存储过程
NSMutableArray *archiveArr = [NSMutableArray arrayWithCapacity:self.STNArrayList.count];
for (STNArrayList *singleList in self.STNArrayList) { NSData *listEncodedObject = [NSKeyedArchiver archivedDataWithRootObject:singleList]; [archiveArr addObject:listEncodedObject]; } //可以将archiveArr存入NSUserDefaults中了
读取过程
NSArray *localSavedArr = ;//从NSUserDefaults中读取本地存储的数据 NSMutableArray *mutableArr = [NSMutableArray arrayWithCapacity:localSavedArr.count]; for (NSData *data in localSavedArr) { STNArrayList *singleList = [NSKeyedUnarchiver unarchiveObjectWithData:data]; [mutableArr addObject:singleList]; } // 现在可以访问mutableArr来获得STNArrayList的值
在STNArrayList类中实现NSCoding协议
- (id)initWithCoder:(NSCoder *)aDecoder { if (self == [super init]) { _title = [aDecoder decodeObjectForKey:JSON_KEY]; } return self; } - (void)encodeWithCoder:(NSCoder *)aCoder { [aCoder encodeObject:_title forKey:JSON_KEY]; }
标签:
原文地址:http://www.cnblogs.com/stonewong/p/4931630.html