我有一个对象数组(自定义对象),它被称为“收藏夹”,当我尝试在NSUserDefault中存储此数组时,我有这个错误
我的代码:
最喜欢的内容 - >来自MyObject类的(object1,object2,object3 ...)
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSData* myClassArrayData = [NSKeyedArchiver archivedDataWithRootObject:favorite];
[defaults setObject:myClassArrayData forKey:@"favorite"];
我的错误:
[MyObject encodeWithCoder:]: unrecognized selector sent to instance
为什么?
答案 0 :(得分:4)
要在您的案例中存储自定义对象MyObject
,该类必须实现NSCoder
界面。
界面只有两种方法:
- (id) initWithCoder:(NSCoder *)aDecoder {
self = [super init];
if (self) {
self.identifier = [aDecoder decodeIntegerForKey:@"identifier"];
self.name = [aDecoder decodeObjectForKey:@"name"];
/* continue with all the properties that need to be restored */
}
return self;
}
- (void) encodeWithCoder:(NSCoder *)aCoder {
[aCoder encodeInteger:self.identifier forKey:@"identifier"];
[aCoder encodeObject:self.name forKey:@"name"];
/* continue with all the properties that need to be saved */
}