Search code examples
iosswiftswift2nsdictionarynsuserdefaults

How do I save NSUserDefaults when dictionary key has a Null value


I have a project using SwiftForms. There is a navbar button that performs an function to send the info in the textFields to NSUserDefaults. But the app crashes if I have an empty textField, but data is saved when all fields are filled out. Do I just add a check in the function to look for NSNull?

func submit(_: UIBarButtonItem!) {
    let message = self.form.formValues()
    //message is [String : AnyObject]
    let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject(message as Dictionary, forKey: "theMessage")
    print("\n Message Saved! \n")
    print(message)
} 

This is the error I get when I click save and don't fill out any fields and the app crashes:

Attempt to set a non-property-list object {
    birthday = "<null>";
    job = "<null>";
    lastName = "<null>";
    name = "<null>";
    segmented = "<null>";
    stepper = 20;
    textview = "<null>";
} as an NSUserDefaults/CFPreferences value for key theMessage

This is what I get when I fill out all the fields - No crash

 --- Message Saved! --- 

["segmented": 1, "job": Job, "lastName": Last, "birthday": 2016-07-01 22:00:12 +0000, "textview": Etiam porta sem malesuada magna mollis euismod. Vestibulum id ligula porta felis euismod semperac, vestibulum at eros., "stepper": 22, "name": First]

Solution

  • formValues returns NSNull for empty values which can't be saved in NSDictionary as noted by Paulw11.

    You can use this function to filter it.

    let filtered = message.filter({!$1.isKindOfClass(NSNull)}).reduce([:]) { ( dic , e) -> [String:AnyObject] in
                var dic = dic
                dic[e.0 as! String] = e.1
                return dic
            }
    

    and then save the filtered in userDefaults