Last active
December 17, 2015 18:39
-
-
Save sharplet/5655202 to your computer and use it in GitHub Desktop.
Category on NSArray to allow subscripting via an NSIndexPath.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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