I'm trying to use a 1D array like a 2D this way but I can't figure it out. Given an array like this:
NSArray *myArray = @[@0,@1,@2,@3,@4,@5];
Is it possible to acces '4' using an NSIndexPath defined like this?:
NSIndexPath *index = [NSIndexPath indexPathForRow:1 inSection:1];
More generally, you can use an index path of dimension A to walk an array of dimension B. You can also make a rule that says what to do when you have extra dimensions in either your path or in your array.
That rule can look something like this: if I run out of path dimensions, return whatever object I find at the end of the path. If I run out of array dimensions (like the case in your question) discard the remainder of the path and return whatever non-array I found.
In code:
- (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];
}
Call it like this...
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]);
This produces the output "there", for the given index path.
I suppose that you want to do something like this:
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]]);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With