Is there an API to use NSIndexPathfor navigating / accessing a nested array design in the iOS SDK? I looked through the docs for NSIndexPathand NSArray?
For instance:
NSArray *nested = @[
@[
@[@1, @2], @[@10, @20]
],
@[
@[@11, @22], @[@110, @220]
],
@[
@[@111, @222], @[@1110, @2220]
]
];
If I wanted to simulate the access path to @ 222, I could compile:
NSIndexPath *path = [[[NSIndexPatch indexPathWithIndex: 2] indexPathByAddingIndex: 0] indexPathByAddingIndex: 1];
So, do I need to write my own recursive accessor?
id probe = nested;
for (NSInteger position = 0; position < path.length; position++) {
probe = probe[path indexAtPosition: position];
}
I would be struck by the fact that Apple went so far as to actually simulate the design, but then did not provide an API to combine the two. I would expect a method on NSArrayor NSIndexPaththat would do something like:
id value = [nested objectAtIndexPath: path];
Or maybe there is a more idiomatic twist that I miss?
UPDATE:
I decided to follow the advice of @CrimsonChris and compiled the following:
NSArray + NestedAccess.h
#import <Foundation/Foundation.h>
@interface NSObject (NestedAccess)
- (id) objectAtPath: (NSIndexPath*) path;
@end
NSArray + NestedAccess.c
#import "NSArray+NestedAccess.h"
@implementation NSArray (NestedAccess)
- (id) objectAtPath: (NSIndexPath*) path {
id probe = self;
for (NSInteger position = 0; position < path.length; position++) {
probe = ((NSArray*)probe)[path indexAtPosition: position];
}
return probe;
}
@end