3.12. Deleting Cells and Sections From Table Views

Problem

You want to delete sections and/or cells from table views using animations.

Solution

In order to delete sections from a table view, follow these steps:

  1. First delete the section(s) in your data source, whether you are using a data model like Core Data or a dictionary/array.

  2. Invoke the deleteSections:withRowAnimation: instance method of UITableView on your table view. The first parameter that you need to pass to this method is of type NSIndexSet and this object can be instantiated using the indexSetWithIndex: class method of NSIndexSet class, where the given index is an unsigned integer. Using this approach, you will be able to delete only one section at a time. If you intend to delete more than one section at a time, use the indexSetWithIndexesInRange: class method of NSIndexSet to create the index set using a range and pass that index set to the aforementioned instance method of UITableView.

If you want to delete cells from your table view, follow these steps:

  1. First, delete the cell(s) from your data source. Again, it doesn’t matter if you are using Core Data, a simple dictionary, array, or anything else. The important thing is to delete the objects that represent the table view cells from your data source.

  2. Now in order to delete the cells that correspond to your data objects, invoke the deleteRowsAtIndexPaths:withRowAnimation: instance method of your table view. The first parameter that you have to pass to this method is an array ...

Get iOS 5 Programming Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.