Skip to content

Instantly share code, notes, and snippets.

@calimarkus
Created August 10, 2012 14:35
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save calimarkus/3314686 to your computer and use it in GitHub Desktop.
Save calimarkus/3314686 to your computer and use it in GitHub Desktop.
Objective-C Literals: Object Subscripting (LLVM 4.0) - ready to use in iOS 5 & 4!
// 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"]);
}
}
//
// 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
//
// 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
@lhasiuk
Copy link

lhasiuk commented Nov 7, 2013

- (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.

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