且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UIPickerView 不会显示从 NSUserDefaults 加载的数据 - 加载数据时应用程序崩溃

更新时间:2023-02-02 13:46:40

pickerViews 为空的原因很可能,因为您没有将它们作为数据源和委托连接到 viewController1.您可以在故事板或代码中执行此操作:

The reason that your pickerViews are empty is most likely because you have not wired them up to viewController1 as dataSource and delegate. You can do this in the storyboard or in code:

override  func viewDidLoad() {
    super.viewDidLoad()
    let pickers = [pickerView1,pickerView2,pickerView3]
    for i in 0...2 {
        let pickerView : UIPickerView = pickers[i]
        pickerView.dataSource = self
        pickerView.delegate = self
    }
}

更新(第 3 部分)

exercisesList 是一个字典数组.例如,您正在向练习列表添加一个新项目:

exercisesList is an array of dictionaries. Here for example you are adding a new item to exercisesList:

 newMutableList.addObject(dataSet)

数据集的创建/定义如下:

where dataSet is created/defined as follows:

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

所以你有一个单项字典,键是练习".

so you have a single-item dictionary, with the key "exercises".

然后在 viewController1 中解压数组并假设它填充了字符串,而不是字典:

Then in viewController1 you are unpacking the array and assuming it is populated with strings, not dictionaries:

return exercises[row] as String

这里是将字典转换为字符串,结果崩溃了.

Here you are casting a dictionary to a string, which is crashing out.

线索在堆栈跟踪行 swift dynamic cast failed在这些行中

The clue is in the stack trace line swift dynamic cast failed and in these lines

 (ObjectiveC.UIPickerView, titleForRow : Swift.Int, forComponent:     
 Swift.Int) => Swift.ImplicitlyUnwrappedOptional<Swift.String>

如果您从字典键exercises"中正确提取字符串作为值,它将起作用:

It will work if you correctly extract the string as a value from the dictionary key "exercises":

        return exercises[row]["exercises"] as String

或者,您可以使用字符串而不是字典来填充数组(因为每个条目只有一个条目).

Alternatively you could populate the array with strings instead of dictionaries (as you only have one entry per entry).

希望你现在可以在不崩溃的情况下运行它!

Hopefully you can run this without crashing now!