Search code examples
iosnsuserdefaultsdata-persistence

saving Set to NSUserDefaults


I am storing a Set into NSUserDefaults with the following code. When I close the app and launch it again it breaks. There is something screwy going on with NSUserDefaults statement, because it works fine if I omit this code. What could be the reason?

var setOfStrings: Set<String>?


 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

        let onlyAtFirstLaunch = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as? Array<String>
        if onlyAtFirstLaunch == nil{
            setOfStrings = Set<String>()

        }else{
            let arrayFromSet = NSUserDefaults.standardUserDefaults().objectForKey("arrayFromSet") as! Array<String>

            setOfStrings! = Set(arrayFromSet)
        }
}



func applicationDidEnterBackground(application: UIApplication) {

    let arrayFromSet = Array(setOfStrings!)


    NSUserDefaults.standardUserDefaults().setObject(NSArray(array: arrayFromSet), forKey: "arrayFromSet")

    NSUserDefaults.standardUserDefaults().synchronize()
}

Solution

  • This line of code is causing the crash:

    setOfStrings! = Set(arrayFromSet)
    

    You are force unwrapping an optional var which is still nil;

    Delete the "!" and it will fix the problem.

    setOfStrings = Set(arrayFromSet)