2012-03-09 25 views
6

Tôi có tình huống dữ liệu nơi tôi muốn sử dụng đường dẫn chỉ mục. Khi tôi duyệt qua dữ liệu tôi muốn tăng nút cuối cùng của một NSIndexPath. Mã tôi có cho đến thời điểm này là:Cách tăng 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); 

Điều này có vẻ hơi, tốt, clunky - Có cách nào tốt hơn để làm điều đó không?

Trả lời

6

Bạn có thể thử này - có lẽ không kém phần phiền phức, nhưng ít nhất là một chút ngắn hơn:

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

Tốt. Tôi thích nó tốt hơn bởi vì nó tránh tất cả các fluffing xung quanh với c mảng. Cảm ơn vì điều đó. – drekka

5

Một dòng ít theo cách này:

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

+0

Điều này sẽ làm việc cho các đường dẫn chỉ mục xem bảng, nhưng nếu tôi nhớ chính xác, tôi đã xem xét một tình huống mà đường dẫn chỉ mục là cho một thứ khác và dài hơn hai nút. – drekka

2

Kiểm tra giải pháp của tôi trên 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 
} 
Các vấn đề liên quan