Error when using NSUserDefaults

223 Views Asked by At

I've been trying for weeks now to save some values in one view controller then access them in another using the NSUserDefaults method. I am using this code:

(to save):

let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Coding Explorer", forKey: "userNameKey")
  • the last line produces an "expected declaration" error

(to get values):

let defaults = NSUserDefaults.standardUserDefaults()
if let name = defaults.stringForKey("userNameKey")
{
    println(name)
}
  • The first of these lines produces a "incorrect redeclarion of 'defaults'"
  • second line produces "expected declaration"
  • third line produces "Consecutive declarions on a line must be seperated by a ;" and "variables used within its own initial value"

Please help me fix this I've tried different lots of code to use NSUserDefaults, and I've tried using the code on separate and the same view controllers.

1

There are 1 best solutions below

0
On

You may try to use this way..

to save first define a string called for example "firstName":

var firstName : String = "Im Swift"

in viewDidLoad in the first ViewController :

if (NSUserDefaults.standardUserDefaults().stringForKey("firstName") == nil){
NSUserDefaults.standardUserDefaults().setObject(firstName, forKey: "firstName")
}

To retrieve value : in the viewDidLoad of second ViewController :

if (NSUserDefaults.standardUserDefaults().stringForKey("firstName") != nil){

var x = NSUserDefaults.standardUserDefaults().objectForKey("firstName") as! String

    println("\(x)");
}