在 UIPickerView 中使用来自 NSUserDefaults 的数据 - pickerView 保持为空

Use data from NSUserDefaults in UIPickerView - pickerView stays empty

我昨晚尝试设置 NSUserDefaults,但一直出现错误:

ViewController3:

保存数据

  @IBAction func tappedAddButton(sender: AnyObject) {

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var exercisesList:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray

    var dataSet:NSMutableDictionary = NSMutableDictionary()
    dataSet.setObject(textField.text, forKey: "exercises")

    if ((exercisesList) != nil){
        var newMutableList:NSMutableArray = NSMutableArray();

        for dict:AnyObject in exercisesList!{
            newMutableList.addObject(dict as NSDictionary)
        }

        userDefaults.removeObjectForKey("exercisesList")
        newMutableList.addObject(dataSet)
        userDefaults.setObject(newMutableList, forKey: "exercisesList")

    }else{
        userDefaults.removeObjectForKey("exercisesList")
        exercisesList = NSMutableArray()
        exercisesList!.addObject(dataSet)
        userDefaults.setObject(exercisesList, forKey: "exercisesList")
    }

    userDefaults.synchronize()

    self.view.endEditing(true)
    textField.text = ""

}

ViewController1:

加载数据

 var exercises:NSMutableArray = NSMutableArray();

...

    override func viewDidAppear(animated: Bool) {

    var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()

    var exercisesListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("exercisesList") as? NSMutableArray

    if ((exercisesListFromUserDefaults) != nil){
        exercises = exercisesListFromUserDefaults!
    }

}

向变量 "exercises" 添加一些数据时,pickerView 保持为空。

您正在使用密钥 "exercisesList" 设置 userDefaults,但试图使用不同的密钥 ("itemList") 取回数据