Wednesday, June 19, 2013

NSIndexPath initWithIndexes example in Objective C (iOS).


NSIndexPath initWithIndexes

Initializes an allocated NSIndexPath object with an index path of a specific length.

- (id)initWithIndexes:(NSUInteger *)indexes length:(NSUInteger)length

Parameters
indexes
Array of indexes to make up the index path.
length
Number of nodes to include in the index path.

Return Value of [NSIndexPath initWithIndexes]
Initialized NSIndexPath object with indexes up to length.

NSIndexPath initWithIndexes example.
NSUInteger x[] = {0 , 0};
NSIndexPath *path = [[NSIndexPath alloc] initWithIndexes: x length: 2];
int row = [path row];
int section = [path section];
row = path.row;
section = path.section;

Example of [NSIndexPath initWithIndexes].
- (void)textFieldDidBeginEditing:(UITextField *)textField {

    //Show the navButtons
    [self navButtonAnimation];

    DetailsStandardCell *cell = (DetailsStandardCell *)textField.superview.superview.superview;

    self.parentController.lastCell = cell;

    //Code to scroll the tableview to the previous indexpath so the previous button will work. NOTE previous button only works if its target table cell is visible.
    NSUInteger row = cell.cellPath.row;
    NSUInteger section = cell.cellPath.section;

    NSIndexPath *previousIndexPath = nil;

    if (cell.cellPath.row == 0 && cell.cellPath.section != 0) //take selection back to last row of previous section
    {
    NSUInteger previousIndex[] = {section -1, ([[self.sections objectForKey:[NSNumber numberWithInt:section - 1]]count] -1)};
    previousIndexPath = [[NSIndexPath alloc] initWithIndexes:previousIndex length:2];  
    }
    else if (cell.cellPath.row != 0 && cell.cellPath.section != 0)
    {
     NSUInteger previousIndex[] = {section, row - 1};
     previousIndexPath = [[NSIndexPath alloc] initWithIndexes:previousIndex length:2];

    }

    [self.theTableView scrollToRowAtIndexPath: cell.cellPath.section == 0 ? cell.cellPath : previousIndexPath atScrollPosition:UITableViewScrollPositionTop animated:YES];

}

NSIndexPath initWithIndexes example.
NSUInteger indexes[2];
[indexPath getIndexes:indexes];
indexes[1]--;
NSIndexPath * adjustedIndexPath = [[NSIndexPath alloc] initWithIndexes:indexes
                                                                length:2];
NSManagedObject * managedObject = [self.fetchedResultsController
                                    objectAtIndexPath:adjustedIndexPath];

End of NSIndexPath initWithIndexes example article.