4

I cannot understand why in the following code, indexPath.section is retuning a null value.

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
    NSLog("Index Path %@", indexPath)
    // Index Path <NSIndexPath: 0x1666d1d0> {length = 2, path = 0 - 0}

    NSLog("Index Path Section %@", indexPath.section)
    // Index Path Section (null)

Following this question I have also tried the following to access the section value:

if let section = indexPath?.section {
    NSLog("Index Path Section %@", section)
}

I have a table with 2 sections with 1 row in each section. On the first iteration where path = 0 - 0, the log shows Index Path Section (null). On the second iteration where path = 1 - 0 the program crashes.

I'm not trying to do anything complicated, I just need to access the section value so that I can conditionally return the correct type of cell.

Community
  • 1
  • 1
PassKit
  • 12,231
  • 5
  • 57
  • 75

1 Answers1

6

You are access the section value correctly. You are just print it the wrong way.

section have type of NSInteger, which is Int in swift

just change log to NSLog("Index Path Section %d", indexPath.section)

It print (null) because the section value is 0. and crashed when it is 1 because it is not valid object pointer

Bryan Chen
  • 45,816
  • 18
  • 112
  • 143
  • Thanks - I managed to figure it out myself. Now I have a problem with dequeuing cells but the compiler in this first seed really doesn't give you much to go on! – PassKit Jun 11 '14 at 06:46
  • Alternatively use the print() and println() methods rather than NSLog, e.g. println("Index Path Section \\(indexPath.section)") – sketchyTech Jun 11 '14 at 08:16