0

I have TableView grouped style with 3 section, I need dynamically add row to this section. When I add:

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

It's okay, but when I change number numberOfRowsInSection I got error:

2017-03-29 04:21:42.032 TableView-Grouped[81597:7624167] *** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSSingleObjectArrayI objectAtIndex:]: index 1 beyond bounds [0 .. 0]'
*** First throw call stack:
(
    0   CoreFoundation                      0x0000000106cc5d4b __exceptionPreprocess + 171
    1   libobjc.A.dylib                     0x0000000103fd821e objc_exception_throw + 48
    2   CoreFoundation                      0x0000000106d1ec2f 

My code:

import UIKit

class ViewController: UITableViewController {

    var arr = ["Row 1", "Row 2", "Row 3"]
    override func viewDidLoad() {
        super.viewDidLoad()

        tableView.dataSource = self
        tableView.delegate = self
        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell")
        tableView.reloadData()

    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    // MARK: - Table view data source

    override func numberOfSections(in tableView: UITableView) -> Int {
        return 3
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 2
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
        cell.textLabel?.text = arr[indexPath.row]
        return cell
    }

}

enter image description here

1 Answers1

0

When i add a row for my custom TableView i need to reload manually the data for the rows:

//swift 2.3
dispatch_async(dispatch_get_main_queue(), { () -> Void in
    self.tableView.reloadData()
})

//swift 3
DispatchQueue.main.async{
    self.tableView.reloadData()
}

If you have a function that append the data arr need to reload in that moment like:

 func refresh() {
        //remove if need
        arr.removeAll()
        self.GetData()
        DispatchQueue.main.async(execute: {
            self.myTable.performSelector(onMainThread: #selector(UICollectionView.reloadData), with: nil, waitUntilDone: true)

        })
    }
Ulises
  • 406
  • 7
  • 22
  • Where i should put DispatchQueue.main.async block ? I puted in viewDidLoad but still actual error – user3544668 Mar 29 '17 at 07:40
  • Put it on the function that actual change the data on your code, if you have a block of code that add the data dynamically you need to put it after that – Ulises Mar 30 '17 at 15:59