Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get "does not implement methodSignatureForSelector" when try to store Array in NSUserDefaults,Swift?

Tags:

swift

I try to store Array of objects in NSUserDefaults.

I have following snippets of code:

    var accounts = MyAccounts()     var array:Array<MyAccounts.MyCalendar> =  accounts.populateFromCalendars()      NSUserDefaults.standardUserDefaults().           setObject(array, forKey: "test_storeAccounts_array") // <- get error here     NSUserDefaults.standardUserDefaults().synchronize() 

But I get Exception:

does not implement methodSignatureForSelector: -- trouble ahead 

my class structure:

class MyAccounts {     /* ... */      class MyCalendar {         var title:String?         var identifier:String?         var email:String?         var calType:String?         var isActive:Bool?         var isMainAcount:Bool?          init(){}     } } 

Any ideas?

like image 726
snaggs Avatar asked Aug 19 '14 11:08

snaggs


2 Answers

Make sure your class inherits from NSObject

class MyAccounts:NSObject {     /* ... */      class MyCalendar {         var title:String?         var identifier:String?         var email:String?         var calType:String?         var isActive:Bool?         var isMainAcount:Bool?          init(){}     } } 
like image 105
mahega Avatar answered Sep 27 '22 19:09

mahega


I was getting this exception in Swift 3.0. In my case, my model class was not inherit from NSObject base class. just inherit my class from NSObject base class and implements NSCoding protocol (if your container array has custom objects)

  class Stock: NSObject, NSCoding {        var stockName: String?        override init() {       }        //MARK: NSCoding protocol methods       func encode(with aCoder: NSCoder){           aCoder.encode(self.stockName, forKey: "name")       }        required init(coder decoder: NSCoder) {            if let name = decoder.decodeObject(forKey: "name") as? String{                self.stockName = name           }       }        func getStockDataFromDict(stockDict stockDict:[String:AnyObject]) -> Stock {             if let  stockName = stockDict["name"] {                 self.stockName = stockName as? String            }             return self        }    } 
like image 34
Himanshu Mahajan Avatar answered Sep 27 '22 18:09

Himanshu Mahajan