2

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?

Deddiekoel
  • 1,939
  • 3
  • 17
  • 25
  • http://stackoverflow.com/questions/22168753/unrecognized-selector-sent-to-instance-while-archiving-data-nscoding – Muhammad Noman Oct 03 '16 at 19:33
  • Let me guess, this worked perfectly for you in the previous version (2.x) of swift right? If so you might want to check http://stackoverflow.com/questions/39827040/swift-3-weird-crashes-type-inference. A completely different situation but the point is the same. There might be a variable where you need to explicitly define the type in order to make it work. Let me know if you know what I mean and if it helps. – Majster Oct 03 '16 at 19:36
  • Haven't tried any other Swift versions. But I did try to explicitly type the properties in the encode function. Even replaced it all with a single print statement. No change to the error. – Deddiekoel Oct 03 '16 at 19:51
  • Currently following a different approach; converting the NSManagedObject to a NSDictionary and exporting that. Using this solution: http://stackoverflow.com/questions/31672558/ios-swift-serialize-a-nsmanagedobject-to-json-with-relationships Still need to find way to import it all again. – Deddiekoel Oct 03 '16 at 20:28
  • Another take on the 'output to dictionary first' is this Gist: https://gist.github.com/nuthatch/5607405 Only it's in Objective C. – Deddiekoel Oct 04 '16 at 06:53

0 Answers0