1

I have two classes both for different UIViewController, in one of the classes i have 3 arrays, and i have added those arrays to a NSUserdefaults, now i want to call those/use those arrays in the other class, how do i do that?

let userDefaults = NSUserDefaults.standardUserDefaults()
    userDefaults.setObject(name, forKey: "ThisContainsName")
    userDefaults.setObject(surname, forKey: "ThisContainsSurname")
    userDefaults.setObject(money, forKey: "ThisContainsBudget")
    userDefaults.synchronize()
1
  • What's wrong with let xyzObjects = userDefaults.arrayForKey("xyz")? Commented Mar 1, 2015 at 1:47

1 Answer 1

1

Just use arrayForKey to get the arrays:

var yourNames =  NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsName")   
var yourSurnames =  NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsSurname") 
var yourMoneys =  NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsBudget")
Sign up to request clarification or add additional context in comments.

5 Comments

If i do this way to get the arrays, suppose in my table view cell i wasn't to se the text equal to the string in the array should i do this way? But i doubt it will work since yourNames is just a variable. cell.textLabel?.text = yourNames[0]
It should work exactly that way you mentioned. Just try yourNames[0].
when i do that i get an error saying [AnyObject]? doesn't have a member names 'subscript' if(names?.isEmpty == false ){ return cell.textLabel?.text = names[0] }
you need to cast your array to stringarray: NSUserDefaults.standardUserDefaults().arrayForKey("ThisContainsName") as [String]
i tried as well, still gives me the same errors message. but this time it says [String]? doesn't have a member names 'subscript'

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.