带有NSCoding的NSManagedObject无法正常工作

时间:2016-10-03 19:20:06

标签: ios swift3 nscoding

我有一个Swift 3 iOS应用程序,我希望能够共享我存储在Core Data中的实体。我所做的是在NSManagedObject类中实现NSCoding:

导入基金会     导入CoreData     导入UIKit

public class Event: NSManagedObject, NSCoding {

    // MARK: NSCoding

    override init(entity: NSEntityDescription, insertInto context: NSManagedObjectContext?) {
        super.init(entity: entity, insertInto: context)
    }

    required public init(coder aDecoder: NSCoder) {
        let ctx = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext
        let entity = NSEntityDescription.entity(forEntityName: "Group", in: ctx)!

        // Note: pass `nil` to `insertIntoManagedObjectContext`
        super.init(entity: entity, insertInto: nil)

        for attribute:String in self.entity.attributesByName.keys{
            self.setValue([aDecoder.decodeObject(forKey: attribute)], forKey: attribute)
        }
    }

    public func encode(with aCoder: NSCoder){
        for attribute:String in self.entity.attributesByName.keys{
            aCoder.encode(self.value(forKey: attribute), forKey: attribute)
        }
    }

}

然后我尝试使用以下方法序列化对象:

    NSKeyedArchiver.archiveRootObject(selectedGroup, toFile: file)

但是当它被执行时,它失败了:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance

所以,即使我已经实现了NSCoding协议,由于某种原因,NSCoding协议似乎并不坚持。知道我做错了吗?

0 个答案:

没有答案