2

I am trying to add Int to an empty Array and then store its data with UserDefaults and then read it , Here is what I am doing :

//create an empty array
var intArray = [Int]()


func addToBookMark(Number:Int) {

    //Add object to array and save it
    intArray.append(Number)

    UserDefaults.standard.set(intArray, forKey: "bookmark")
    UserDefaults.standard.synchronize()


    //Read it
    let array = UserDefaults.standard.array(forKey: "bookmark")  as? [Int] ?? [Int]()
    print(array.description)

}

//Calling the method :
addToBookMark(Number: 30)

The problem is compiler gives me an empty array: [] What is my problem ?

7
  • Are you checking in simulator or playground? Commented May 10, 2017 at 7:15
  • @SivajeeBattina playground Commented May 10, 2017 at 7:16
  • The code you have written won't work in simulator or playground. Check in device. The syntax to store/get array from user defaults changed from swift 3.0 Commented May 10, 2017 at 7:18
  • If you want it to work in simulator and playground also, you need to archieve the array using NSKeyedArchiver and store it. Commented May 10, 2017 at 7:21
  • your code is fine and correct Commented May 10, 2017 at 7:22

1 Answer 1

2

Your code is perfect, its the issue of simulators. So better try rebooting your Mac.

WWDC Seed: Running multiple iOS simulators can cause NSUserDefaults to not work

Running an iOS 8 or 9 simulator followed by an iOS 10 simulator will cause NSUserDefaults to stop working in the simulator. This can be worked around by rebooting the host Mac.

In case of Playground , there is a radar regarding it as it not works on it since playground doesn't have access to sandbox.

Sign up to request clarification or add additional context in comments.

Comments

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.