简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM