NSUserDefaults Not Saving TextField Text (Swift)

前端 未结 5 1972
天涯浪人
天涯浪人 2021-01-01 05:52

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(&         


        
相关标签:
5条回答
  • 2021-01-01 06:02

    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)
        }
    
    0 讨论(0)
  • 2021-01-01 06:03
    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
    
    0 讨论(0)
  • 2021-01-01 06:13
    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)
    
    0 讨论(0)
  • 2021-01-01 06:21

    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.
    
    0 讨论(0)
  • 2021-01-01 06:25

    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")!)
    
    0 讨论(0)
提交回复
热议问题