-3

我有一个对象数组(自定义对象),它被称为“收藏夹”,当我尝试将此数组存储在 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

为什么?

4

1 回答 1

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  */
}
于 2013-06-06T14:09:25.403 回答