Skip to content

Instantly share code, notes, and snippets.

@sharplet
Last active December 17, 2015 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharplet/5655202 to your computer and use it in GitHub Desktop.
Save sharplet/5655202 to your computer and use it in GitHub Desktop.
Category on NSArray to allow subscripting via an NSIndexPath.
//
// Category on NSArray to allow subscripting via an NSIndexPath.
//
// Adam Sharp
// May 27, 2013
//
// Given this array:
//
// NSArray *matrix = @[
// @[ @1, @2 ],
// @[ @3, @4 ]
// ];
//
// It can be subscripted like so:
//
// NSIndexPath *indexPath = [NSIndexPath indexPathForRow:1 inSection:0];
// matrix[indexPath]; // => @2
//
@interface NSArray (indexPathKeyedSubscript)
@end
@implementation NSArray (indexPathKeyedSubscript)
- (id)objectForKeyedSubscript:(id)key
{
NSParameterAssert([key isKindOfClass:[NSIndexPath class]]);
NSIndexPath *indexPath = (NSIndexPath *)key;
NSUInteger length = indexPath.length;
NSUInteger *indexes = malloc(sizeof(NSUInteger) * length);
[indexPath getIndexes:indexes];
id memo = self;
for (int i = 0; i < length; i++) {
NSAssert([memo respondsToSelector:@selector(objectAtIndexedSubscript:)],
@"expected child collection '%@' to respond to objectAtIndexedSubscript:", memo);
memo = memo[indexes[i]];
}
free(indexes);
return memo;
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment