0

Click here to see the screenshot of the code.

I'm making a list application and I'm saving the array for the "list" that i wanna load when i open the app again. the weird thing is that i works on a simulator but not on a device. (See the screenshot to understand)

        feedCells = (NSUserDefaults.standardUserDefaults().objectForKey("feedCellsData") as? [String])!  

thats the line that it keeps crashing on.

I've tried to change it so it's an optional value. But i can't find anything that seems to help..

1 Answer 1

1

First of all check that your device iOS version is iOS 8 or higher. If it is less than that then also use synchronize() after setting value to NSUserDefaults.

You are forcefully unwrapping (using !) an optional value which you are getting from Down Casting (using as?).

You can also resolve this crash by adding a check for the value which you are fetching from the NSUserDefaults for not nil and then assign it to your feedCells var.

let cells = NSUserDefaults.standardUserDefaults().objectForKey("feedCellsData") as? [String]
if cells != nil {
    feedCells = cells
}

or

Make feedCells var an optional and remove "!" from the end of the line which is getting the error.

var feedCell : [String]?
feedCells = NSUserDefaults.standardUserDefaults().objectForKey("feedCellsData") as? [String]
Sign up to request clarification or add additional context in comments.

2 Comments

This helped soooo much. There should be more people like you!
Accept & Up Vote the answer by clicking on the Right & Up Arrow button if it helped you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.