IndexPath

A UITableView consists of a vertical list of sections. Each section consists of a vertical list of UITableViewCells. Each cell contains a line of text or an image, and maybe also an accessory such as a checkmark or a disclosure indicator (shaped like a >). To see the classic table, open the Settings app on your iPhone.

To identify a cell in a table view we must specify its section number, and its row number within that section. Both numbers are zero-based. For example, the first cell in the first section is (0, 0). A table view that is not divided into sections is treated as one big section whose section number is 0.

An IndexPath object contains a pair of Int properties, section and row, giving the section number and row number of a UITableViewCell within a UITableView.

For the time being, we will put only two numbers into an NSIndexPath. But a later example will exploit the fact that an NSIndexPath can hold more than two numbers. When we write them, they are conventionally separated by periods: 10.20.30.40.50. This series of numbers would be used by apps like the Settings app, where we navigate from table to table to table. As we drill deeper, the index path gets longer.

Source code in IndexPath.zip

  1. Class AppDelegate. I wrote the entire demonstration in the application(_:didFinishLaunchingWithOptions:) method.

Output

section = 20
row = 10

index 0 = 10
index 1 = 20
index 2 = 30
index 3 = 40
index 4 = 50

index 0 = 10
index 1 = 20
index 2 = 30
index 3 = 40
index 4 = 50
index 5 = 60