hybrid Dev
hybrid Dev

Reputation: 529

no data available label is not showing in table view

I have one view controller with the table view. when there is data it will populate in the table view. When there is no data, then no data label have to display. I used below code. But its crash on this line:

func numberOfSections(in tableView: UITableView) -> Int {

    var numOfSection: NSInteger = 0

    if (self.alldata?.count)! > 0 {

        self.tableView.backgroundView = nil
        numOfSection = 1

    } else {

        let rect = CGRect(x: 0,
                          y: 0,
                          width: self.tableView.bounds.size.width,
                          height: self.tableView.bounds.size.height)
        let noDataLabel: UILabel = UILabel(frame: rect)

        noDataLabel.text = "No Data Available"
        noDataLabel.textColor = UIColor(red: 22.0/255.0, green: 106.0/255.0, blue: 176.0/255.0, alpha: 1.0)
        noDataLabel.textAlignment = NSTextAlignment.center
        self.tableView.backgroundView = noDataLabel

    }
    return numOfSection

}

Crash on this line: if (self.alldata?.count)! > 0 { crash : (lldb). no further info i am getting.

Thanks in advance!

Upvotes: 0

Views: 65

Answers (3)

mag_zbc
mag_zbc

Reputation: 6992

Change (self.alldata?.count)! > 0 to self.alldata?.count ?? 0 > 0. You are force-unwrapping the result of (self.alldata?.count) so if alldata is nil you are force-unwrapping a nil;

On the side note, it is a very bad practice to have side effects in such functions as numberOfSections. That function should only return the number of sections and do nothing more. Put your UI manipulation somewhere else.

Upvotes: 1

Subramanian P
Subramanian P

Reputation: 4375

You are forcefully unwrapping the array, which is nil at the time of no data. Due to that it's crashing.

Check like this

if let alldata = self.alldata, alldata.count > 0 {
      self.tableView.backgroundView = nil
      numOfSection = 1
}

Upvotes: 1

Aravind A R
Aravind A R

Reputation: 2714

The crash maybe because alldata is nil and you try to unwrap it in (self.alldata?.count)!. Try modifying it like

if self.alldata.count != nil && (self.alldata?.count)! > 0 {
    self.tableView.backgroundView = nil
    numOfSection = 1
}

Upvotes: 0

Related Questions