2
  1. Description:

    A table view with 3 rows is created when the app is started. A add button in the navigation bar will add a new row into the table view if tapped. The core process behind the add row action is the method func insertRows(at:, with:).

    Apple documents and many stack-overflow answers (e.g., this one) suggest that put any method calls that insert, delete, or select rows and sections of the table view between function beginUpdates() and endUpates().

    I removed the beginUpdates() and endUpdates(); it turns out the app works just fine without them.

  2. Question:

    What are the benefits of adding beginUpdates() & endUpdates()?

  3. Why I ask this question:

    The function func insertRows(at:, with:) is calling the delegate function tableView(_:, cellForRowAt:) -> UITableViewCell to create a new cell via dequeueReusableCell(withIdentifier:, for:) -> UITableViewCell, this is the same procedural the tableView creates the 3 default rows when the app started, but, there is no such a beginUpdates / endUpdates there. So why do I need to add this procedure later when I add a new row, while without them the app still seems to be working?

gung - Reinstate Monica
  • 11,583
  • 7
  • 60
  • 79
SLN
  • 4,772
  • 2
  • 38
  • 79
  • **I removed the beginUpdates() and endUpdates() it turns out the app works just fine without them.** -- > Without reload data how it can be working fine, You either use beginUpdates() & endUpdates or reload data to update / Animate your tableview – Prashant Tukadiya Jun 22 '17 at 12:28
  • 2
    [Related](https://stackoverflow.com/q/23260279/335858) – Sergey Kalinichenko Jun 22 '17 at 12:30
  • @AmritTiwari Could you please stop COPY and PASTE from other's answer such as this one: https://stackoverflow.com/a/23260386/3004698 – SLN Jun 22 '17 at 12:48
  • 1
    Option-click on `beginUpdates` and read the pop-up. It is for grouping multiple inserts or deletes that you want to animate all at once. There's no need for `begin/endUpdates` for a single insertion or deletion. – vacawama Jun 22 '17 at 12:54

1 Answers1

2

To animate a batch insertion, deletion, and reloading of rows and sections, call the corresponding methods within an animation block defined by successive calls to beginUpdates and endUpdates. If you don’t call the insertion, deletion, and reloading methods within this block, row and section indexes may be invalid. Calls to beginUpdates and endUpdates can be nested; all indexes are treated as if there were only the outer update block.

At the conclusion of a block—that is, after endUpdates returns—the table view queries its data source and delegate as usual for row and section data. Thus the collection objects backing the table view should be updated to reflect the new or removed rows or sections.

Apple Docs

Harshal Valanda
  • 5,331
  • 26
  • 63