AlmoDev
AlmoDev

Reputation: 969

Getting index out of error when reloading table view

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    let order =  orders[indexPath.row]
    guard orders.count > indexPath.row else {
        print("Index out of range")
        return
    }
    
    let storyboard = UIStoryboard(name: "Main", bundle: nil)
    var viewController = storyboard.instantiateViewController(withIdentifier: "viewControllerIdentifer") as! OrderDetailsController
    viewController.passedValue = order.id
    self.present(viewController, animated: true , completion: nil)      
}

Whenever I close my app (go to background) and reopen it it crashes.

fatal error: Index out of range

2017-06-18 18:09:33.726310 JaeeDriver[1378:563304] fatal error: Index out of range

I have no idea why it does this. It's important to note that in ViewDidLoudI have this line of code to update my table

var timer = Timer.scheduledTimer(
    timeInterval: 4, 
    target: self, 
    selector: "GetOrders", 
    userInfo: nil, 
    repeats: true
)

and whenever the update happens, I have this code in the beginning of GetOrders function

func GetOrders (){   
    orders = []
    ...
}

to remove the old data and replace it with the new one

Update

at the end of GetOrder

func GetOrders (){   
    orders = []
    ....
    ....
    DispatchQueue.main.async {
        self.tableview.reloadData()
    }
}
       

number of sections and rows :

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return orders.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
     let cell = tableView.dequeueReusableCell(withIdentifier: "OrderCell", for: indexPath) as! OrderCell
    
    let entry = orders[indexPath.row]
    
    cell.DateLab.text = entry.date
     cell.shopNameLab.text = entry.shopname
    cell.shopAddLab.text = entry.shopaddress
    cell.nameClientLab.text = entry.clientName
    cell.clientAddLab.text = entry.ClientAddress
    cell.costLab.text = entry.Cost
    cell.perefTimeLab.text = entry.PerferTime
    cell.Shopimage.hnk_setImage(from: URL(string: entry.Logo))
    return cell
}

Any help please would be appreciated.

Upvotes: 0

Views: 1994

Answers (1)

Jitendra Tanwar
Jitendra Tanwar

Reputation: 249

I think you should need to add one more array say temporder . add fresh list in this after getting fresh list change array data of order with temporder and reload it. You are clearing order data and selecting list item from table view. But at that time fresh data didn't added in order array .

Upvotes: 1

Related Questions