Search code examples
iosarraysswiftnsdata

Converting Swift Array to NSData causes an error


I have two arrays

var questions: [Question]!
var types: [[Type]]!

I am trying to convert those two arrays to NSData. I do like below

let typesData = NSKeyedArchiver.archivedDataWithRootObject(types)
let questionsData = NSKeyedArchiver.archivedDataWithRootObject(questions)

As soon as it hits typesData, the app crashes and throws an error like following:

*** NSForwarding: warning: object 0x15e5a4100 of class '(app Name).Type' does not implement methodSignatureForSelector: -- trouble ahead Unrecognized selector -[(app Name).Type replacementObjectForKeyedArchiver:]

I am assuming it's causing an error since those arrays has custom types. Is there any way I can convert those arrays to NSData? Any solutions for solving this problem will be appreciated.


Solution

  • For swift, you need to implement this in your Object (Question, Type) class like so:

    class ItemObject:NSObject, NSCoding {
        var itemName = ""
        var itemCheck = false
    
        func encodeWithCoder(aCoder: NSCoder) {
            aCoder.encodeObject(itemName, forKey:"itemName")
            aCoder.encodeBool(itemCheck, forKey:"itemCheck")
        }
    
    
        required init (coder aDecoder: NSCoder) {
            self.itemName = aDecoder.decodeObjectForKey("itemName") as! String
            self.itemCheck = aDecoder.decodeBoolForKey("itemCheck")
        }
    
        override init() {
            super.init()
        }
    }
    

    This is also required for store custom object to NSUserDefaults and CoreData