Daniil Gavrilov
Daniil Gavrilov

Reputation: 47

Can't insert object in the array, that I want add to User Defaults

I have initialization of the array

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

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?


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

Upvotes: 3

Views: 6181

Answers (1)

Rob Napier
Rob Napier

Reputation: 299633

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 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.

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.

Upvotes: 4

Related Questions