247

I need delete row 1 of a table in a function I have defined. In order to use deleteRowAtIndexPath you must use an IndexPath with a section and row defined. How can I create an indexpath like this?

An array with the int {1} as its only member will crash; the NSLog message states that the section needs to be defined as well.

*Edit -> Code relating to cell delete:

    NSIndexPath *myIP = [[NSIndexPath alloc] indexPathForRow:0 inSection:0];
    NSArray *myArray = [[NSArray alloc] initWithObjects:myIP, nil];
//  [self.tableView beginUpdates];
    [self.tableView deleteRowsAtIndexPaths:myArray withRowAnimation:UITableViewRowAnimationFade];
//  [self.tableView endUpdates];
comrade
  • 4,590
  • 5
  • 33
  • 48
Rubber Duck
  • 2,997
  • 2
  • 20
  • 25

4 Answers4

648

Use [NSIndexPath indexPathForRow:inSection:] to quickly create an index path.

Edit: In Swift 3:

let indexPath = IndexPath(row: rowIndex, section: sectionIndex)

Swift 5

IndexPath(row: 0, section: 0)
Blazej SLEBODA
  • 8,936
  • 7
  • 53
  • 93
Ben Gottlieb
  • 85,404
  • 22
  • 176
  • 172
127

indexPathForRow is a class method!

The code should read:

NSIndexPath *myIP = [NSIndexPath indexPathForRow:0 inSection:0] ;
Paras Joshi
  • 20,427
  • 11
  • 57
  • 70
verec
  • 5,224
  • 5
  • 33
  • 40
18

Obligatory answer in Swift : NSIndexPath(forRow:row, inSection: section)

You will notice that NSIndexPath.indexPathForRow(row, inSection: section) is not available in swift and you must use the first method to construct the indexPath.

JohnVanDijk
  • 3,546
  • 1
  • 24
  • 27
17

For Swift 3 it's now: IndexPath(row: rowIndex, section: sectionIndex)

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
comrade
  • 4,590
  • 5
  • 33
  • 48