fs_tigre fs_tigre - 1 year ago 75
iOS Question

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

How to prevent crashes when an array is empty and you make a request from a UITableView or UIPickerView?

My current method is to always initialize my arrays before using them with dummy data but I'm not really happy with this method since sometimes the dummy data is not needed and even-worse, sometimes it doesn't even make sense to show the data, in fact most of the time what I want is to show an empty table if there is no data.

For instance if I will be retrieving an array from

to be used in a
I usually initialize it in the
as follow...


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

Again, how can I safely use an un-initialized array in a
and show an empty table?

Answer Source

There is no need to put "dummy data" in your array. You can just initilize an empty array. like below

    var myArray = [String]()

And in numberOfRowsInSection return myArray.count. If count is zero, cellForRowAtIndexPath will not be called and you are safe to go.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download