NSManagedObject可以符合NSCoding [英] Can NSManagedObject conform to NSCoding

查看:117
本文介绍了NSManagedObject可以符合NSCoding的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在设备之间传输单个对象。现在我把我的NSManagedObject转换为字典,存档和发送为NSData。收到我放弃它。但我真的想通过归档和取消归档而不是创建中间数据对象来传输NSManagedObject本身。

I need to transfer a single object across device. Right now I am converting my NSManagedObject to a dictionary , archiving it and sending as NSData. Upon receiving I am unarchiving it. But I would really like to transfer the NSManagedObject itself by archiving and unarchiving instead of creating an intermediate data object.

@interface Test : NSManagedObject<NSCoding>
@property (nonatomic, retain) NSString * title;
@end

@implementation Test
@dynamic title;

- (id)initWithCoder:(NSCoder *)coder {
    self = [super init];
    if (self) {
        self.title = [coder decodeObjectForKey:@"title"]; //<CRASH
    }
    return self;
}
- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:self.title forKey:@"title"];
}
@end


NSData *archivedObjects = [NSKeyedArchiver archivedDataWithRootObject:testObj];
NSData *objectsData = archivedObjects;
if ([objectsData length] > 0) {
    NSArray *objects = [NSKeyedUnarchiver unarchiveObjectWithData:objectsData];
}

上述代码的问题是。它在 initWithCoder 中的 self.title 崩溃,表示无法识别的选择器发送到实例。

The problem with the above code is. It crashes at self.title in initWithCoder saying unrecognized selector sent to instance.


  • 为什么 title 未被识别为选择器。

  • 应该在 initWithCoder ?中创建对象之前,以某种方式使用nil受管对象上下文吗?

  • 覆盖 copyWithZone

  • Why is title not being recognized as a selector.
  • Should unarchive use a nil managed object context somehow before creating the object in initWithCoder?
  • Do i need to override copyWithZone?

推荐答案

下面的代码段应该做的伎俩。主要区别是调用 super initWithEntity:insertIntoManagedObjectContext:

This snippet below should do the trick. The main difference is to call super initWithEntity:insertIntoManagedObjectContext:

- (id)initWithCoder:(NSCoder *)aDecoder {
   NSEntityDescription *entity = [NSEntityDescription entityForName:@"Test" inManagedObjectContext:<YourContext>];

   self = [super initWithEntity:entity insertIntoManagedObjectContext:nil];
   NSArray * attributeNameArray = [[NSArray alloc] initWithArray:self.entity.attributesByName.allKeys];

   for (NSString * attributeName in attributeNameArray) {
        [self setValue:[aDecoder decodeObjectForKey:attributeName] forKey:attributeName];
   }
   return self;
}

(请参阅此链接如何获取< YourContext>

上面的代码片段只处理属性,没有关系。处理关系 NSManagedObjectID 使用 NSCoding 是可怕的。如果你确实需要带来关系,考虑在解码时引入一个额外的属性来匹配两个(或许多)实体。

Above snippet will handle only the attributes, no relationships. Dealing with relationships as NSManagedObjectID using NSCoding is horrible. If you do need to bring relationships across consider introducing an extra attribute to match the two (or many) entities when decoding.

这篇关于NSManagedObject可以符合NSCoding的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆