我是一名新的IOS开发人员。我正在使用Xcode 8和swift 3。 我想从保存在Core数据库中的数据中将值显示到pickerView中。我的代码有一个错误(致命错误:索引超出范围)
我定义了一个数组来保存Core数据库中提取的数据
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]
}
答案 0 :(得分:0)
使用以下语句声明数组:
var boundName = [String]()
以这种方式声明不指定数组的大小,因此当您运行以下行时,它将崩溃:
boundName [row] = boundText!
<强>解决方案:强>
改为使用append
:
boundName.append(boundText!)