public
Last active

Objective-C Literals: Object Subscripting (LLVM 4.0) - ready to use in iOS 5 & 4!

  • Download Gist
NSContainer+Subscripting.h
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
//
// NSContainer+Subscripting.h
//
// Created by Markus Emrich on 10.08.12.
// Copyright 2012 nxtbgthng. All rights reserved.
//
 
#if !defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
 
#import "NSContainer+Subscripting.h"
 
@interface NSArray (Subscripting)
- (id)objectAtIndexedSubscript:(NSInteger)index;
@end
 
@interface NSMutableArray (MutableSubscripting)
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index;
@end
 
@interface NSDictionary (Subscripting)
- (id)objectForKeyedSubscript:(id)key;
@end
 
@interface NSMutableDictionary (MutableSubscripting)
- (void)setObject:(id)object forKeyedSubscript:(id)key;
@end
 
#endif
NSContainer+Subscripting.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
//
// NSContainer+Subscripting.m
//
// Created by Markus Emrich on 10.08.12.
// Copyright 2012 nxtbgthng. All rights reserved.
//
 
#if !defined(__IPHONE_6_0) || __IPHONE_OS_VERSION_MIN_REQUIRED < __IPHONE_6_0
 
#import "NSContainer+Subscripting.h"
 
@implementation NSArray (Subscripting)
- (id)objectAtIndexedSubscript:(NSInteger)index {
return [self objectAtIndex:index];
}
@end
 
@implementation NSMutableArray (MutableSubscripting)
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index {
[self insertObject:anObject atIndex:index];
}
@end
 
@implementation NSDictionary (Subscripting)
-(id)objectForKeyedSubscript:(id)key {
return [self objectForKey: key];
}
@end
 
@implementation NSMutableDictionary (MutableSubscripting)
- (void)setObject:(id)object forKeyedSubscript:(id)key {
[self setObject:object forKey: key];
}
@end
 
#endif
main.m
Objective-C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
// example
 
int main(int argc, char *argv[])
{
@autoreleasepool {
NSMutableArray *array = [NSMutableArray arrayWithObject: @"vorher"];
NSLog(@"%@", array[0]);
array[0] = @"haha";
NSLog(@"%@", array[0]);
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
dict[@"test"] = @"jap";
NSLog(@"%@", dict[@"test"]);
dict[@"test"] = @"change";
NSLog(@"%@", dict[@"test"]);
}
}
- (void)setObject:(id)anObject atIndexedSubscript:(NSUInteger)index {
    [self insertObject:anObject atIndex:index];
}

is incorrect. It should use replaceObjectAtIndex:withObject in cases where the index refers to an existing element.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.