我知道有很多关于此错误的问题,但我浏览了所有这些问题,但没有一个有帮助。我从主类中调用函数 addCell() ,下面的代码是我的 TableViewControllerClass 中的代码。我肯定在我的 .storyboard 中链接了 requestIdentifier“cell”,并且数组“locations”和“times”绝对不为空,因为我在错误发生时打印它们,所以问题必须出在我的“table”变量上,它也正确链接到 TableView ,但由于某种原因显然为零。有什么建议吗?
func addCell(){
//update to insertion sort
currLocation = addLocation
if (locations == [""] && times == [0]) {
self.locations.removeAll()
self.times.removeAll()
}
if !(locations.isEmpty){
if locations[locations.count-1] != currLocation {
var count = 0
var neverVisited = true
for location in locations{
if location == currLocation{
neverVisited = false
times[count] += addTime
count++
}
}
if neverVisited {
locations.append(currLocation)
times.append(addTime)
}
} else {
times[times.count-1] = addTime
}
} else {
locations.append(currLocation)
times.append(addTime)
}
print(locations) //not empty
print(times) //not empty
table.reloadData() //crashes here
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel?.text = locations[indexPath.row] + ", \(times[indexPath.row])"
}
return cell
}
最佳答案
您可以在调用 reloadData 函数之前在 addCell() 函数的末尾或开头(取决于您是否想要执行所有逻辑,即使表尚不存在)使用保护语句来解决问题:
guard let tmpTable = table else {
return
}
您还可以使用:
if let tmpTable = table else {
tmpTable.reloadData()
}
这样,仅当您的表已加载时才会调用导致问题的函数。 另外,使用主类有点奇怪,通常这个类不用于执行任何代码/逻辑,请尝试使用正确的 Controller 。
关于iOS - fatal error : unexpectedly found nil while unwrapping an Optional value when reloadData() is called,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38731814/