0

由于我们不能直接将 NSArray 存储在核心数据中,因此我通过将数组转换为 NSData 将 NSManagedObject 数组存储到另一个 NSManagedObject 中。存储在该数组中的 NSManagedObject 符合 NSCoding 协议,并且我在这些类中实现 NSCoding 协议的方法以存档它们。

@implementation MyClass
   - (void)encodeWithCoder: (NSCoder *)coder
{
    [coder encodeObject: [self canPay] forKey: @"canPay"];
    [coder encodeObject: [self guestId] forKey: @"guestId"];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{

 if((self = [self init]))
     if (self)
     {
         [self setCanPay: [aDecoder decodeObjectForKey: @"canPay"]];
         [self setGuestId: [aDecoder decodeObjectForKey: @"guestId"]];
     }

    return self;
}

使用以下代码行将 MyClass 数组保存为 NSData

NSData *myData = [NSKeyedArchiver archivedDataWithRootObject:arrayContainingMyClass];
[myEntity setMyClassData:myData];

问题是在取消归档 myClassData 时,我遇到了异常......

 NSData *newdata = [NSData dataWithData:myEntity.myClassData];
    NSMutableArray *arr = [NSMutableArray arrayWithArray: [NSKeyedUnarchiver unarchiveObjectWithData:newdata]];

在第二行中,我遇到了异常,

由于未捕获的异常“NSInvalidArgumentException”而终止应用程序,原因:“-[MyClass setCanPay:]:无法识别的选择器发送到实例 0x743c950”

4

1 回答 1

2

You're calling self = [self init] in initWithCoder:, you need to call self = [super initWithCoder:aDecoder]. But even then I'm not sure that's going to work. Core Data manages its own objects (hence the name NSManagedObject), so I don't know if storing them yourself by means of NSKeyed(Un)Archiver is going to end well for you.

Your best bet is to use Core Data relationships so it can handle all the storing for you.

于 2013-07-23T12:38:31.573 回答