2012-03-09 29 views
6

Tengo una situación de datos en la que deseo utilizar una ruta de índice. A medida que recorro los datos, quiero incrementar el último nodo de un NSIndexPath. El código que tengo hasta ahora es:Cómo incrementar un NSIndexPath

int nbrIndex = [indexPath length]; 
NSUInteger *indexArray = (NSUInteger *)calloc(sizeof(NSUInteger),nbrIndex); 
[indexPath getIndexes:indexArray]; 
indexArray[nbrIndex - 1]++; 
[indexPath release]; 
indexPath = [[NSIndexPath alloc] initWithIndexes:indexArray length:nbrIndex]; 
free(indexArray); 

Esto se siente un poco, bueno, torpe - ¿Hay una mejor manera de hacerlo?

Respuesta

6

Puede probar esto - tal vez igualmente torpe, pero por lo menos un poco más corto:

NSInteger newLast = [indexPath indexAtPosition:indexPath.length-1]+1; 
indexPath = [[indexPath indexPathByRemovingLastIndex] indexPathByAddingIndex:newLast]; 
+0

Agradable. Me gusta más porque evita todo el abultamiento con matrices c. Gracias por eso. – drekka

5

Una línea de menos de esta manera:

indexPath = [NSIndexPath indexPathForRow:indexPath.row+1 inSection:actualIndexPath.section];

+0

Esto funcionará para rutas de índice de vista de tabla, pero si mal no recuerdo estaba considerando una situación en la que la ruta de índice era para algo más y más larga que dos nodos. – drekka

2

comprobar mi solución en Swift:

func incrementIndexPath(indexPath: NSIndexPath) -> NSIndexPath? { 
    var nextIndexPath: NSIndexPath? 
    let rowCount = numberOfRowsInSection(indexPath.section) 
    let nextRow = indexPath.row + 1 
    let currentSection = indexPath.section 

    if nextRow < rowCount { 
     nextIndexPath = NSIndexPath(forRow: nextRow, inSection: currentSection) 
    } 
    else { 
     let nextSection = currentSection + 1 
     if nextSection < numberOfSections { 
      nextIndexPath = NSIndexPath(forRow: 0, inSection: nextSection) 
     } 
    } 

    return nextIndexPath 
} 
Cuestiones relacionadas