gpt4 book ai didi

arrays - 显示核心数据库中 PickerView 的值

转载 作者:行者123 更新时间:2023-11-30 12:56:26 25 4
gpt4 key购买 nike

我是一名新的 IOS 开发人员。我正在使用 Xcode 8 和 swift 3。我想将核心数据库中保存的数据的值显示到 pickerView 中。我的下面的代码有一个错误( fatal error :索引超出范围)

我定义一个数组来保存从核心数据库获取的数据

  var boundName  = [String]()
var expenses = [NSManagedObject]()// variable to fetch the data from core database
var num = 0// variable to hold the count of the fetched data

这是pickerView的函数

public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1;
}

func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {

let request = NSFetchRequest <NSFetchRequestResult> (entityName : "ExpenseBound_Table")
request.returnsObjectsAsFaults = false


do {
expenses = try self.context.fetch(request) as! [NSManagedObject]
num = expenses.count

} catch { print(error) }

return num;
}

func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {


let request = NSFetchRequest <NSFetchRequestResult> (entityName : "ExpenseBound_Table")
request.returnsObjectsAsFaults = false

do{
expenses = try self.context.fetch(request) as! [NSManagedObject]

if expenses.count > 0 {


let person = expenses[row]
let boundText = person.value(forKey: "boundName_Expense" ) as? String
boundName [row] = boundText! //error fires here fatal error: Index out of range




}

}
catch{
print ("Fetch Faield")
}
return boundName[row]
}

最佳答案

数组使用以下方式声明:

var boundName = [String]()

这种方式的声明不会指定数组的大小,因此当您运行以下行时,它将崩溃:

boundName [row] = boundText!

解决方案:

使用append代替:

boundName.append(boundText!)

关于arrays - 显示核心数据库中 PickerView 的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40346032/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com