Can't insert object into array which I want to add to custom defaults

I have an array initialization

    var defaults = NSUserDefaults.standardUserDefaults()
    var initObject: [CPaymentInfo]? = defaults.objectForKey("paymentData") as? [CPaymentInfo]
    if initObject == nil {
        initObject = [CPaymentInfo]()
        defaults.setValue(initObject, forKey: "paymentData")
    }
    defaults.synchronize()

      

And I have a controller that contains two text labels and two buttons: Save and Discard (both segment calls)

    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")
    }

      

But it doesn't work and the application crashes. I found that I can just set "payments" as the new default object for the key without changing (Commenting out the block with insert). Also I found that I can only comment out the line with the setObject method and apps will work too. How can I do what I want?


2015-07-14 20: 34: 34.403 cash app [15156: 1494701] Property list is invalid for format: 200 (Property lists cannot contain objects of type 'CFType') 2015-07-14 20: 34: 34.404 cash app [15156 : 1494701] Attempted to set a non-property object ("cash_app.CPaymentInfo") as the NSUserDefaults / CFPreferences value for a key payment. Date 2015-07-14 20: 34: 34.409 cash app [15156: 1494701] *** Application terminated due to uncaught exception "NSInvalidArgumentException", reason: "Attempt to insert a non-property object list (" cash_app.CPaymentInfo ") for key paymentDate '

+3


source to share


1 answer


The answer is in the error message:

Attempt to insert non-property list object ( "cash_app.CPaymentInfo" ) for key paymentData'

      



You cannot put arbitrary classes in a property list (for example NSUserDefaults

). There is a specific list of classes that are acceptable. If you have other classes that you want to keep, you need to convert them to an acceptable class.

For documentation on saving non-property property classes to user defaults, see Storing NSColor in UserDefaults . While this article is dedicated NSColor

, it applies to any object that matches NSCoding

. See also the note in Introduction to Property Lists .

+4


source







All Articles