为什么在UITableViewController中使用NSCoding会出错?

时间:2015-09-19 05:25:56

标签: ios swift nscoding

我使用NSCoding来存储数据持久性 这是我的代码

class CenterRecordTableViewController: UITableViewController {

   private var records:[ReplayListData] = []

   override func encodeWithCoder(aCoder: NSCoder) {
      super.encodeWithCoder(aCoder)
      aCoder.encodeObject(self.records, forKey: "records")
   }

   required  init(coder aDecoder: NSCoder!) {
      super.init(coder: aDecoder)
      if let res = aDecoder.decodeObjectForKey("records") as? [ReplayListData] {
         self.records = res
      }
   }

   override func viewDidLoad() {
      super.viewDidLoad()
      loadLocalData()
      if records.count > 0 {
          getDataFromServer()
      }
   }

   func loadLocalData(){
        if let data = NSUserDefaults.standardUserDefaults().objectForKey("CenterRecords") as? NSData {
            let obj = NSKeyedUnarchiver.unarchiveObjectWithData(data) as! CenterRecordTableViewController
            self.records = obj.records
        }
    }

    func saveLocalData(){
        let data = NSKeyedArchiver.archivedDataWithRootObject(self)
        NSUserDefaults.standardUserDefaults().setObject(data, forKey: "CenterRecords")
        NSUserDefaults.standardUserDefaults().synchronize()
    }

    func getDataFromServer(){
         //get data from server
        saveLocalData()
    }

}

但是当我运行应用程序时,错误是hppen in

aCoder.encodeObject(self.records, forKey: "records")

这是控制台输出:

2015-09-19 13:09:57.219 test[41108:3488786] *** NSForwarding: warning: object 0x182651f0 of class 'test.ReplayListData' does not implement methodSignatureForSelector: -- trouble ahead
Unrecognized selector -[test.ReplayListData replacementObjectForKeyedArchiver:]

修改

这是ReplayListData的代码我删除了其他变量

class ReplayListData {
    var created:Int
    init(a:Int){
        self.created = a
    }
}

EDIT2

我尝试继承NSObject

中的ReplayListData
class ReplayListData:NSObject {
   var created:Int
   init(a:Int){
       self.created = a
   }
}

应用程序崩溃,但控制台正在更改

[test.ReplayListData encodeWithCoder:]: unrecognized selector sent to instance 0x17173970
2015-09-19 13:34:14.407 test[41238:3492144] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[test.ReplayListData encodeWithCoder:]: unrecognized selector sent to instance 0x17173970'
*** First throw call stack:
(0x2431cd67 0x31dbdc77 0x2432222d 0x24320109 0x24251938 0x24fc0425 0x24fc162f 0x24fc1c11 0x24fc0425 0x258d30 0x258eb8 0x24fc0425 0x24fc67c1 0x2599c8 0x25fa58 0x28b328 0x1a8f9cb 0x1a8f9b7 0x1a93411 0x242e2c41 0x242e1361 0x2422e981 0x2422e793 0x2b5af051 0x27820981 0x312da8 0x32359aaf)
libc++abi.dylib: terminating with uncaught exception of type NSException

0 个答案:

没有答案