我试图使用像2D这样的1D数组,但我无法弄清楚。给定如下数组:
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"。
我想你应该这样做:
NSArray* array= @[ @[ @1,@2,@3 ] , @[@2, @4, @6] ];
NSIndexPath* path=[[NSIndexPath alloc]initWithIndexes: (const NSUInteger[]){0,0} length:2];
NSLog(@"%@",array [[path indexAtPosition: 1]] [[path indexAtPosition: 0]]);
NSArray* myArray= @[ @[ @"Zero.Zero",@"Zero.One",@"Zero.Two" ] , @[ @"One.Zero", @"One.One", @"One.Two" ] ] ;
NSLog(@"%@", myArray[1][2] ) ; // logs 'One.Two'