1
votes

I am writing an iOS app in Swift.

Whenever the page loads it gets the list of movies from server and it populates that list into tableView.

I wrote the code for getting JSON from server in a static library (Objective-C) and am receiving json to app via Notification design pattern.

  override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(ReceivedNListOfMoviesNotification(_:)), name: Notification.Name(VUSDK.basicNotificationName()), object: nil)
    requestForData() 
  }

  func ReceivedNListOfMoviesNotification(_ notification:NSNotification)
  {
      if let info = notification.userInfo {         
        basicArray=info["Search"] as! [Any]
        if basicArray.count>0 {
            tableView.beginUpdates()
            self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic)                    
            tableView.endUpdates()
        }
      }
   }

But app is crashing:

*** Assertion failure in -[UITableView _endCellAnimationsWithContext:], /BuildRoot/Library/Caches/com.apple.xbs/Sources/UIKit_Sim/UIKit-3600.7.47/UITableView.m:1737 2017-04-23 13:49:12.562 VUDemo[4835:164247] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid update: invalid number of rows in section 0. The number of rows contained in an existing section after the update (10) must be equal to the number of rows contained in that section before the update (0), plus or minus the number of rows inserted or deleted from that section (1 inserted, 0 deleted) and plus or minus the number of rows moved into or out of that section (0 moved in, 0 moved out).'

1
Where do you add the corresponding item in the data source array? You have first to insert the item in the data source array and then insert the row. Btw: Delete the begin- / endUpdates lines. They have no effect.vadian
basicArray=info["Search"] as! [Any]Atif Shabeer
In this case don't call insert.... Call tableView.reloadData() instead.vadian
Kindly check the project, I want to reload data incrementally, ie, fetch data from server on every time user scrolls to bottom of tableViewAtif Shabeer

1 Answers

1
votes

Replace

   if basicArray.count>0 {
        tableView.beginUpdates()

        self.tableView.insertRows(at: [IndexPath.init(row: self.basicArray.count-1, section: 0)], with: .automatic)

        tableView.endUpdates()
   }

with

   if !basicArray.isEmpty {
       tableView.reloadData()
   }

because you are overwriting the entire array rather than adding a single item.