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

后端 未结 4 618
死守一世寂寞
死守一世寂寞 2020-12-24 12:53

I try to store Array of objects in NSUserDefaults.

I have following snippets of code:

    var accounts = MyAccounts()
    var array:Arra         


        
相关标签:
4条回答
  • 2020-12-24 13:07

    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
           }
       }
    
    0 讨论(0)
  • 2020-12-24 13:17

    You need to convert the class into NSData first. Something like this:

    var data = NSKeyedArchiver.archivedDataWithRootObject(accounts.populateFromCalendars())
    
    var userDefaults = NSUserDefaults.standardUserDefaults();
    userDefaults.setObject(data, forKey: "test_storeAccounts_array"); 
    
    0 讨论(0)
  • 2020-12-24 13:28

    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(){}
        }
    }
    
    0 讨论(0)
  • 2020-12-24 13:34

    In Swift 2, I experienced similar error while using the Notification Pattern within a custom class. Note that when the same notification(Observe) is implemented in a ViewController class , it doesn't complain. Its only with the custom class, created from a Swift file without subclassing this error was thrown

    class myClass : NSObject {
          override init(){
                super.init()
                NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("functionCall:"), name: "NotificationName", object: nil)
            }
    
        //Implement function
        func functionCall(notification: NSNotification) {
    
        //Extract the object and implement the function
        }
        }
    
    0 讨论(0)
提交回复
热议问题