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
@mttrb
Copy link
Author

mttrb commented Oct 13, 2015

If the index is negative it is used as an offset from the end of the array instead of the beginning. For example, the last element of the array will have an index of -1, the second last element has an index of -2. This is a common feature in scripting languages.

My code doesn't contain any error handling as that will be handled by the original swizzled methods.

This really shouldn't be used in production code as I can't even think of all the things that could go wrong with it.

@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