Skip to content

Instantly share code, notes, and snippets.

@mttrb
Created November 15, 2012 02:54
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mttrb/4076357 to your computer and use it in GitHub Desktop.
Save mttrb/4076357 to your computer and use it in GitHub Desktop.
Objective-C Literals: Negative Array Subscripts
//
// NSArray+NegativeIndexes.m
// Allow Negative Array Literals
//
// Created by Matthew Robinson on 25th October 2012.
// Copyright (c) 2012 Matthew Robinson. All rights reserved.
//
// WARNING: This is a proof of concept and should not be used
// in production code. This could break at anytime.
#import <Foundation/Foundation.h>
#if __has_feature(objc_subscripting)
#import <objc/runtime.h>
@implementation NSArray (NegativeIndexes)
+ (void)load {
method_exchangeImplementations(
class_getInstanceMethod(self, @selector(objectAtIndexedSubscript:)),
class_getInstanceMethod(self, @selector(BLC_objectAtIndexedSubscript:))
);
}
- (id)BLC_objectAtIndexedSubscript:(NSInteger)idx {
if (idx < 0) {
idx = [self count] + idx;
}
return [self BLC_objectAtIndexedSubscript:idx];
}
@end
@implementation NSMutableArray (NegativeIndexes)
+ (void)load {
method_exchangeImplementations(
class_getInstanceMethod(self, @selector(setObject:atIndexedSubscript:)),
class_getInstanceMethod(self, @selector(BLC_setObject:atIndexedSubscript:))
);
}
- (void)BLC_setObject:(id)anObject atIndexedSubscript:(NSInteger)idx {
if (idx < 0) {
idx = [self count] + idx;
}
[self BLC_setObject:anObject atIndexedSubscript:idx];
}
@end
#endif
@mickeyl
Copy link

mickeyl commented Mar 11, 2016

Great stuff. This inspired me to https://gist.github.com/mickeyl/d266e567da2e3af2ac0b

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment