39

Basically I am storing an index of an array in a NSInteger. I now need it as an NSIndexpath, I'm struggling to see and find a way to convert my NSInteger to NSIndexpath so I can reuse it.

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Dan
  • 1,447
  • 2
  • 14
  • 30
  • What do you need the `NSIndexPath` for? Do you need it for a `UITableView`? – albertamg Jun 23 '11 at 13:34
  • It's used when calling a update statement for sqlite. I think I now converted to NSIndexPath but I need NSIndexPath.row and this throws an error. Any ideas? – Dan Jun 23 '11 at 14:09
  • You can **not** call `row` on an index path created with `indexPathWithIndex:`. To create an index path you can call `row` on it, you can use `indexPathForRow:inSection:`. – albertamg Jun 23 '11 at 14:20

4 Answers4

91

For an int index:

NSIndexPath *path = [NSIndexPath indexPathWithIndex:index];

Creates Index of the item in node 0 to point to as per the reference.

To use the indexPath in a UITableView, the more appropriate method is

NSIndexPath *path = [NSIndexPath indexPathForRow:row inSection:section];
ageektrapped
  • 14,482
  • 7
  • 57
  • 72
8

If you need a NSIndexPath for a UITableView, you can use indexPathForRow:inSection: (reference). Index paths passed to table view must contain exactly two indices specifying the section and row. An index path created with indexPathWithIndex: only contains one index and won't work with a table view.

albertamg
  • 28,492
  • 6
  • 64
  • 71
3

Use below methods of NSIndexPath class.

+ (id)indexPathWithIndex:(NSUInteger)index;
+ (id)indexPathWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length;
- (id)initWithIndex:(NSUInteger)index

Use as below and also Don't forget to release myIndexPath object after using.

NSIndexPath *myIndexPath = [[NSIndexPath alloc] initWithIndex:[myIntObj intValue]];
Jhaliya - Praveen Sharma
  • 31,697
  • 9
  • 72
  • 76
2

Swift 3:

let indexPath = IndexPath(row: 0, section: 0)
David Seek
  • 16,783
  • 19
  • 105
  • 136