Skip to content

Instantly share code, notes, and snippets.

@onmyway133
Forked from mttrb/NSArray+NegativeIndexes.m
Last active August 29, 2015 14:05
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 onmyway133/9e41097bc68bb295d721 to your computer and use it in GitHub Desktop.
Save onmyway133/9e41097bc68bb295d721 to your computer and use it in GitHub Desktop.
//
// 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) {
return nil;
}
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) {
return;
}
[self BLC_setObject:anObject atIndexedSubscript:idx];
}
@end
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment