问题描述
我已初始化数组
var defaults = NSUserDefaults.standardUserDefaults()
var initObject: [CPaymentInfo]? = defaults.objectForKey("paymentData") as? [CPaymentInfo]
if initObject == nil {
initObject = [CPaymentInfo]()
defaults.setValue(initObject, forKey: "paymentData")
}
defaults.synchronize()
我有Controller,包含两个文本标签和两个按钮:保存和取消(同时调用segue)
And I have the Controller, that contains two text labels and two buttons: Save and Cancel (Both calling the segue)
if sender as? UIBarButtonItem == saveButton {
var defaults = NSUserDefaults.standardUserDefaults()
var payments: [CPaymentInfo]? = defaults.objectForKey("paymentData") as? [CPaymentInfo]
var newPaymentItem: CPaymentInfo?
if discriptionField.hasText() {
newPaymentItem = CPaymentInfo(value: (valueField.text as NSString).doubleValue, discription: discriptionField.text)
} else {
newPaymentItem = CPaymentInfo(value: (valueField.text as NSString).doubleValue)
}
if let newPay = newPaymentItem {
payments?.insert(newPay, atIndex: 0)
}
defaults.setObject(payments, forKey: "paymentData")
}
但它不工作和应用程序崩溃。
我发现我可以设置付款作为新的对象在默认的键,而不改变
(通过插入块的注释)。
我也发现,我可以评论行setObject方法,应用程序也将工作。我如何做我想做的?
But it doesn't work and app crashes.I found that I can just set "payments" as new object in defaults for key without changing(By commenting of block with insert).Also I found, that I can comment line with setObject method only and apps will work too. How I can do what I want?
推荐答案
答案在错误信息中:
Attempt to insert non-property list object ( "cash_app.CPaymentInfo" ) for key paymentData'
您不能将任意类放入属性列表(例如 NSUserDefaults
)。有一个可接受的类的特定列表。如果你有其他类,你想存储,你需要将它们转换为可接受的类。
You cannot put arbitrary classes into a property list (such as NSUserDefaults
). There is a specific list of classes that are acceptable. If you have other classes you want to store, you need to convert them to an acceptable class.
有关将非属性列表类保存为用户默认值的文档,请参阅。虽然该文章侧重于 NSColor
,但它适用于符合 NSCoding
的任何对象。另请参阅媒体资源列表简介 a>。
For documentation on saving non-property-list classes to user defaults, see Storing NSColor in UserDefaults. While that article focuses on NSColor
, it applies to any object that conforms to NSCoding
. See also the Note at Introduction to Property Lists.
这篇关于无法在数组中插入对象,我想将其添加到用户默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!