Skip to content

Instantly share code, notes, and snippets.

@zwaldowski
Forked from mikeash/test.m
Created July 13, 2012 17:44
Show Gist options
  • Save zwaldowski/3106221 to your computer and use it in GitHub Desktop.
Save zwaldowski/3106221 to your computer and use it in GitHub Desktop.
Cocoa array slicing
// clang -framework Foundation -fobjc-arc -O3 test.m
#import <Foundation/Foundation.h>
@interface NSNumber (RangeCreation)
- (NSValue *): (NSInteger)length;
@end
@implementation NSNumber (RangeCreation)
- (NSValue *): (NSInteger)length
{
return [NSValue valueWithRange: NSMakeRange([self integerValue], length)];
}
@end
@interface NSArray (RangeSlicing)
- (id)objectForKeyedSubscript: (id)subscript;
@end
@implementation NSArray (RangeSlicing)
- (id)objectForKeyedSubscript: (id)subscript
{
NSValue *slice = subscript;
return [self subarrayWithRange: [slice rangeValue]];
}
@end
int main(int argc, char **argv)
{
@autoreleasepool
{
NSMutableArray *array = [NSMutableArray array];
for(int i = 0; i < 100; i++)
[array addObject: @(i * i)];
NSArray *sliced = array[[@5:8]];
NSLog(@"%@", sliced);
}
}
// 2012-07-09 17:15:12.705 a.out[84967:707] (
// 25,
// 36,
// 49,
// 64,
// 81,
// 100,
// 121,
// 144
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment