我有一个自定义对象的数组。当我尝试将该数组保存到NSUserDefaults时,我必须对它们进行归档。以下是我用于归档自定义对象数组的方法:
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//3
var allMessages = defaults.objectForKey(UserDefaultsMesssageKey) as! [AddMessageViewController.harassText]
var aMessage = AddMessageViewController.harassText(phoneNumber: 0, message: "1", frequency: 1, active: 1)
allMessages.append(aMessage)
saveMessage(allMessages)
return (allMessages.count)
}
func archiveMessage(message:[AddMessageViewController.harassText]) -> NSData {
let archivedObject = NSKeyedArchiver.archivedDataWithRootObject(message as NSArray)
return archivedObject
}
func saveMessage(messages: [AddMessageViewController.harassText]) {
let archivedObject = archiveMessage(messages)
defaults.setObject(archivedObject, forKey: UserDefaultsMesssageKey)
defaults.synchronize()
}
func retrieveData()-> [AddMessageViewController.harassText]? {
if let unarchiveObject = NSUserDefaults.standardUserDefaults().objectForKey(UserDefaultsMesssageKey) as? NSData {
return NSKeyedUnarchiver.unarchiveObjectWithData(unarchiveObject) as? [AddMessageViewController.harassText]
}
return nil
}
流程如下:
On saveMessage call, pass the custom array in to get archived. Here is what the array looks like to GDB. You can see that it is an array, and it has 1 class object contained in it.
([Harass_Your_Kate.AddMessageViewController.harassText]) $R0 = 1 value { [0] = 0x00007fa5ab409600 { ObjectiveC.NSObject = { isa = Harass_Your_Kate.AddMessageViewController.harassText } phoneNumber = 0 message = "1" frequency = 1 active = 1 } }
The array gets passed into archiveMessage. The code immediately fails on the NSKeyedArchiver method. The Error message is as follows :
[_TtCC16Harass_Your_Kate24AddMessageViewController10harassText encodeWithCoder:]: unrecognized selector sent to instance 0x7fa5ab409600
2016-07-15 16:31:26.019 Harass Your Kate[5858:7847495] * -[NSKeyedArchiver dealloc]: warning: NSKeyedArchiver deallocated without having had -finishEncoding called on it. 2016-07-15 16:31:26.023 Harass Your Kate[5858:7847495] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[_TtCC16Harass_Your_Kate24AddMessageViewController10harassText encodeWithCoder:]: unrecognized selector sent to instance 0x7fa5ab409600
编辑:这是我的对象定义:
class Text : NSObject {
var phoneNumber = 0 //Text address to send to
var message: String = "" //Message to be sent
var frequency = 24 //Number of hours between messages (usually a multiple of 24 - 24 = daily)
var active = 0 // 0 if cancelled, 1 if active
init(phoneNumber: Int, message: String, frequency: Int, active: Int ){
self.phoneNumber = phoneNumber
self.message = message
self.frequency = frequency
self.active = active
}
}
initWithCoder
和encodeWithCoder
)。 - Duncan C