-
-
Save onmyway133/9e41097bc68bb295d721 to your computer and use it in GitHub Desktop.
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
// | |
// 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