Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mapping 2D NSArray into 1D with NSIndexPath

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];
like image 669
Karlos Zafra Avatar asked Oct 22 '22 21:10

Karlos Zafra


2 Answers

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.

like image 68
danh Avatar answered Oct 27 '22 19:10

danh


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]]);
like image 45
Ramy Al Zuhouri Avatar answered Oct 27 '22 20:10

Ramy Al Zuhouri