NSUserDefaults Not Saving TextField Text (Swift)

2020-02-26 13:13发布

I'm trying to create a game with Swift, and I want to add the ability to create a username, which will be saved in NSUserDefaults. This is my code:

println("Textfield Text: \(usernameTextfield.text)")

NSUserDefaults.standardUserDefaults().setObject(usernameTextfield.text, forKey:"Username")
NSUserDefaults.standardUserDefaults().synchronize()

println(NSUserDefaults.standardUserDefaults().objectForKey("Username") as? String)

The output is:

Textfield Text: MyUsername

nil

The only explanation I can see as to why it is printing nil is that either the saving or the loading of the username is failing. Is there any way this can be corrected or am I doing something wrong?

Any help is appreciated!

5条回答
我只想做你的唯一
2楼-- · 2020-02-26 13:44

In Swift 3.0

    let userDefult = UserDefaults.standard //returns shared defaults object.

    if let userName = usernameTextfield.text {
        //storing string in UserDefaults
        userDefult.set(userName, forKey: "userName") //Sets the value of the specified default key in the standard application domain.
    }

    print(userDefult.string(forKey: "userName")!)//Returns the string associated with the specified key.
查看更多
ゆ 、 Hurt°
3楼-- · 2020-02-26 13:46
In Swift 4.1

 UserDefaults.standard.set(textfield.text, forKey: "yourKey") // saves text field text
  UserDefaults.standard.synchronize()

// To Retrieve
textfield.text = UserDefaults.standard.value(forKey:"yourKey") as? String
查看更多
Ridiculous、
4楼-- · 2020-02-26 13:47

I made a small modification to Roman's answer with Swift 2.0 and Xcode 6.4.

saving:

    var myValue:NSString = usernameTF.text

    NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"Username")
    NSUserDefaults.standardUserDefaults().synchronize()

retrieving:

var myOutput = NSUserDefaults.standardUserDefaults().objectForKey("Username")
if (myOutput != nil)
{
    self.title = "Welcome "+((myOutput) as! String)
    }
查看更多
我想做一个坏孩纸
5楼-- · 2020-02-26 13:49

For swift 3.0, You can create user default by,

UserDefaults.standard.set("yourValue", forKey: "YourString")

To Print the value in console :

print(UserDefaults.standard.string(forKey: "YourString")!)
查看更多
地球回转人心会变
6楼-- · 2020-02-26 13:57
println("Textfield Text: \(usernameTextfield.text)")

var myValue:NSString = usernameTextfield.text

NSUserDefaults.standardUserDefaults().setObject(myValue, forKey:"Username")
NSUserDefaults.standardUserDefaults().synchronize()

var myOutput: AnyObject? = NSUserDefaults.standardUserDefaults().objectForKey("Username")
println(myOutput)
查看更多
登录 后发表回答