Kar*_*fra 5 arrays objective-c multidimensional-array
我试图像这样使用像2D这样的一维数组,但我无法弄明白.给定这样的数组:
NSArray *myArray = @[@0,@1,@2,@3,@4,@5];
Run Code Online (Sandbox Code Playgroud)
是否可以使用这样定义的NSIndexPath访问'4'?:
NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:1];
Run Code Online (Sandbox Code Playgroud)
更一般地,您可以使用维度 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];
}
Run Code Online (Sandbox Code Playgroud)
像这样称呼它...
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]);
Run Code Online (Sandbox Code Playgroud)
对于给定的索引路径,这会生成“there”的输出。
| 归档时间: |
|
| 查看次数: |
1222 次 |
| 最近记录: |