使用Core Data存储自定义对象 [英] Storing custom objects with Core Data
问题描述
我试图存储一个由VOs(NameVO)与Core Data组成的NSMutableArray,但是会抛出以下异常:
'NSInvalidArgumentException',reason:' - [NameVO encodeWithCoder:]:无法识别的选择器发送到实例0x1096400a0'
我的NameVO只是一个简单的值对象,扩展NSObject并包含两个字段,一个字符串和一个NSMutableArray本身包含字符串。它还包含一个比较函数。
我试图准备这个存储为一个CD可变属性类型('names'是我的NameVO数组):
NSData * tempNamesData = [NSKeyedArchiver archivedDataWithRootObject:names];
我的问题是:我需要做什么来使NameVO被NSKeyedArchiver接受才能成功到NSData?
我不想让NameVO扩展NSManagedObject,因为我不能直接实例化和初始化。
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
应该排序您的问题。
// EXTENDED
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [ super init];
if(self){
_formId = [aDecoder decodeObjectForKey:@FormID];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.formId forKey:@FormID];
}
I'm trying to store a NSMutableArray consisting of VOs (NameVO) with Core Data but getting the following exception thrown:
'NSInvalidArgumentException', reason: '-[NameVO encodeWithCoder:]: unrecognized selector sent to instance 0x1096400a0'
My NameVO is just a simple value object, extending NSObject and contains two fields, a string and a NSMutableArray that itself contains strings. It also contains a compare function.
I'm trying to prepare this to be stored as a CD transformable attribute type with ('names' is my NameVO array):
NSData *tempNamesData = [NSKeyedArchiver archivedDataWithRootObject:names];
My question is: what do I need to do to make NameVO be accepted by NSKeyedArchiver to convert it successfully to a NSData?
I don't want NameVO to extend NSManagedObject because then I cannot instantiate and init it directly.
As your exception says you need to implement NSCoding
protocol to your class and you have to override two methods:
- (void)encodeWithCoder:(NSCoder *)aCoder;
- (id)initWithCoder:(NSCoder *)aDecoder;
It should sorted your issue.
// EXTENDED
- (id)initWithCoder:(NSCoder *)aDecoder
{
self = [super init];
if (self) {
_formId = [aDecoder decodeObjectForKey:@"FormID"];
}
return self;
}
- (void)encodeWithCoder:(NSCoder *)aCoder
{
[aCoder encodeObject:self.formId forKey:@"FormID"];
}
这篇关于使用Core Data存储自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!