当数组为空并且您从UITableView或UIPickerView发出请求时,如何防止崩溃?
我当前的方法是始终在将数组与伪数据一起使用之前初始化我的数组,但是我对此方法并不满意,因为有时不需要伪数据,甚至更糟,有时显示数据甚至没有意义。 ,实际上大部分时间我想要的是在没有数据的情况下显示一个空表。
例如,如果我要从NSUserDefaults
中检索要在UITableView
中使用的数组,通常会在AppDelegate
中对其进行初始化,如下所示:
AppDelegate.swift:
NSUserDefaults.standardUserDefaults().registerDefaults([
keyMyAarray:["Dummy Data"]// initializing array
])
SomeViewController:
var myArray = read content from NSUserDefaults...
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
fun tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell = UITableViewCell()
cell.textLabel.text = myArray[indexPath.row]
return cell
}
同样,如何安全地在
UITableView
中使用未初始化的数组并显示一个空表?
最佳答案
无需在阵列中放入“虚拟数据”。您可以只初始化一个空数组。像下面
var myArray = [String]()
并在
numberOfRowsInSection
中返回myArray.count。如果count为零,则不会调用cellForRowAtIndexPath
,您可以放心。
关于ios - 如何安全地在UITableView中使用未初始化的数组并显示一个空表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39593900/