I have a Swift 3 iOS app in which I want to be able to share an entity I store in Core Data. What I've done is implement NSCoding in the NSManagedObject class:
import Foundation import CoreData import 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)
}
}
}
I then try to the serialize the object using:
NSKeyedArchiver.archiveRootObject(selectedGroup, toFile: file)
But when this gets executed it fails with:
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_SwiftValue encodeWithCoder:]: unrecognized selector sent to instance
So, even though I've implemented the NSCoding protocol, for some reason the NSCoding protocol doesn't seem to stick. Any idea what I'm doing wrong?