0

I've always struggled with arrays; I´m trying to save some arrays into user defaults. my arrays are String, Double and UIImageView type. I declared them like:

var nameHospital = [String]()
var distanceBetweenLocations = [Double]()
var images = [UIImage]() // <-- Haven't tried with this yet

and I try to save them in UserDefaults like this...

UserDefaults.standard.set(nameHospital, forKey: "name")

And call theme like so

UserDefaults.standard.object(forKey: "name")

Then when I want to print them to see if it worked, it only prints one value (last value of the For Cycle) then I set my print inside the for and as I was expecting, it printed the value and then replaced it for the next value and so on.

What am I doing wrong? How can I call each value separately for further functions? And How can I do this but with my UIImage array? Thank you for your answers.

2
  • 1
    Edit your question with actual code that is causing you issues. Commented May 26, 2017 at 3:21
  • 2
    And please read the documentation for UserDefaults. It tells you what you can store. Commented May 26, 2017 at 3:21

1 Answer 1

1

You are see this one : NSUserDefault

SAVE :

 let kUserDefault = NSUserDefaults.standardUserDefaults()
 kUserDefault.setObject(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
 kUserDefault.synchronize()

READ :

kUserDefault.arrayForKey("nameArray")!
kUserDefault.objectForKey("nameArray")!
kUserDefault.valueForKey("nameArray")

For Swift 3

let kUserDefault = UserDefaults.standard
kUserDefault.set(["KIRIT" , "MODI" , "FIRST" , "LAST"], forKey: "nameArray")
kUserDefault.synchronize()

let data = kUserDefault.array(forKey: "nameArray")! as? [String] ?? [String]()
print(data)

for more info visit store value in userDefaults

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

1 Comment

@Foolish, thanks to improved the answer.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.