如何在 UITableView 中安全地使用未初始化的数组并显示空的 table

How can I safely use an un-initialized array in a UITableView and show an empty table

当数组为空并且您从 UITableView 或 UIPickerView 发出请求时如何防止崩溃?

我目前的方法是在将数组与虚拟数据一起使用之前始终初始化我的数组,但我对这种方法并不满意,因为有时不需要虚拟数据,甚至更糟的是,有时甚至不需要有意义地显示数据,实际上大多数时候我想要的是如果没有数据则显示一个空 table。

例如,如果我要从 NSUserDefaults 中检索一个数组以用于 UITableView,我通常会在 AppDelegate 中初始化它,如下所示...

AppDelegate.swift:

    NSUserDefaults.standardUserDefaults().registerDefaults([
        keyMyAarray:["Dummy Data"]// initializing array
     ])

一些视图控制器:

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 中使用未初始化的数组并显示一个空的 table?

默认 3 个空行。

var myArray:Array<String>? = ...

func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return 1
}

fun tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return myArray?.count ?? 3
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {        
    var cell = UITableViewCell()
    if let arrayStrings = myArray, arrayStrings.count > indexPath.row {
       cell.textLabel.text = arrayStrings[indexPath.row]
    } 
    return cell
}

无需将 "dummy data" 放入您的数组中。您可以只初始化一个空数组。如下图

    var myArray = [String]()

并在 numberOfRowsInSection return myArray.count。如果计数为零,cellForRowAtIndexPath 将不会被调用,您可以安全离开。