我正在尝试以这种方式使用像二维数组一样的一维数组,但我无法弄清楚。 给定一个这样的数组:
NSArray *myArray = @[@0,@1,@2,@3,@4,@5];
是否可以使用这样定义的 NSIndexPath 访问“4”?:
NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:1];
最佳答案
更一般地说,您可以使用维度 A 的索引路径来遍历维度 B 的数组。您还可以制定一个规则,说明当您的路径或数组中有额外维度时要做什么。
该规则可能看起来像这样:如果我用完了路径维度,则返回我在路径末尾找到的任何对象。如果我用完了数组维度(就像你问题中的情况)丢弃路径的剩余部分并返回我找到的任何非数组。
在代码中:
- (id)objectInArray:(id)array atIndexPath:(NSIndexPath *)path {
// the end of recursion
if (![array isKindOfClass:[NSArray self]] || !path.length) return array;
NSUInteger nextIndex = [path indexAtPosition:0];
// this will (purposely) raise an exception if the nextIndex is out of bounds
id nextArray = [array objectAtIndex:nextIndex];
NSUInteger indexes[27]; // maximum number of dimensions per string theory :)
[path getIndexes:indexes];
NSIndexPath *nextPath = [NSIndexPath indexPathWithIndexes:indexes+1 length:path.length-1];
return [self objectInArray:nextArray atIndexPath:nextPath];
}
这样调用它......
NSArray *array = [NSArray arrayWithObjects:@1, [NSArray arrayWithObjects:@"hi", @"there", nil], @3, nil];
NSIndexPath *indexPath = [NSIndexPath indexPathWithIndex:1];
indexPath = [indexPath indexPathByAddingIndex:1];
NSLog(@"%@", [self objectInArray:array atIndexPath:indexPath]);
这会为给定的索引路径生成输出“there”。
关于objective-c - 使用 NSIndexPath 将 2D NSArray 映射到 1D,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13979938/