所以,我想创建自己的迷你社交网络。在注册页我有以下代码行:

var ns = NSUserDefaults.standardUserDefaults()
let array: [String] = ["\(login!)","\(password!)","\(nameSurname!)", "team", "university"] //team, university
ns.setObject(array, forKey: "\(login)")

我只是创建数组并将其设置为NSUserDefaults。
我还有一个页面,用户可以在其中更改有关他们的信息或数据,例如更改他们的密码。在本页中,我有以下几行代码:
let login = loginTextField.text!
        let password = passwordTextField.text!
        let nameSurname = nameSurnameTextField.text!
        let team = teamTextField.text!
        let university = universityTextField.text!

            let ns = NSUserDefaults.standardUserDefaults()
            let array: [String] = ["\(login)","\(password)","\(nameSurname)", "\(team)", "\(university)"] //team, university course
            ns.setObject(array, forKey: "\(login)")

在这里,我创建了一个新数组,并将这个新数组设置为KEY Login。但是我在NSUserDefaults中的数据没有改变。我怎么能修好它?我该怎么办?谢谢)

最佳答案

不知道这里有什么问题。首先更改:

    var ns = NSUserDefaults.standardUserDefaults()
    //No need for " quotation marks you are using String vars
    let array: [String] = [login!, password!, nameSurname!, team, university]
    ns.setObject(array, forKey: "login")

    //Save the changes
    ns.synchronize()


    //Now when we want to load the information
    let ns = NSUserDefaults.standardUserDefaults()
    let array = ns.objectForKey("login")
    //This prints the users password
    print(array![1])



    //Make some changes
    let newArray = ["new name", password!, nameSurname!, team, university]
    ns.setObject(newArray, forKey: "login")
    //Remember to save
    ns.synchronize()

确保您正在使用ns.synchronize()

关于ios - swift :如何更新NSUserDefault?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/36868375/

10-13 09:25