MhammedMohie
MhammedMohie

Reputation: 312

nscoder swift cannot be sent to an abstract object of class NSCoder

I'm trying to implement autocorrection through SymSpell

I've created the dictionary in the container app and should save it and read it from the keyboard extension

the dictionary contains a dictionaryItem object which needs to be serialized to be saved by NSCoder

I tried to add the methods to the object but I got an error "init(coder adecoder nscoder) swift cannot be sent to an abstract object of class NSCoder"

required init(coder aDecoder: NSCoder) {
   if let suggestions = aDecoder.decodeObjectForKey("suggestions") as? [Int] {
      self.suggestions = suggestions
  }
      if let count = aDecoder.decodeObjectForKey("count") as? Int {
         self.count = count
      }
}
func encodeWithCoder(aCoder: NSCoder) {
     if let count = self.count as? Int {
        aCoder.encodeObject(count, forKey: "count")
     }
    if let suggestions = self.suggestions as? [Int] {
        aCoder.encodeObject(suggestions, forKey: "suggestions")
     }
}

Any thoughts how to fix this?

Upvotes: 3

Views: 3745

Answers (1)

Alessandro Ornano
Alessandro Ornano

Reputation: 35402

import Foundation

class SuggestionModel: NSObject, NSCoding {
    var suggestions: [Int]?
    var count : Int?

    required init(coder aDecoder: NSCoder) {
        self.suggestions = aDecoder.decodeObjectForKey("suggestions") as? [Int]
        self.count = aDecoder.decodeObjectForKey("count") as? Int
        super.init()
    }

    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(self.count, forKey: "count")
        aCoder.encodeObject(self.suggestions, forKey: "suggestions")
    }

    override init() {
        super.init()
    }
}

Upvotes: 1

Related Questions