Key access in NSDictionary using [key] notation?

I just realized that I can access NSDictionary using both objectForKey: and dict [key]?

 NSDictionary *coordsDict = @{@"xpos": @5.0, @"ypos": @7.2, @"zpos": @15.7}; NSLog(@"XPOS: %@", coordsDict[@"xpos"]); NSLog(@"XPOS: %@", [coordsDict objectForKey:@"xpos"]); 

Can someone tell me if this is hiding from me all the time or if its a fairly recent change in language?

EDIT: The question is not generally related to new string literals, but more specifically to accessing an NSDictionary with the same string literal syntax that you would use for NSArray. I obviously missed this and just wanted to check when this syntax was added.

+6
source share
2 answers

This is a new addition to Xcode 4.4+ and relies on the Apple LLVM + Clang compiler. This is a new feature: Arrays can also be accessed with the same notation: myObjectArray[4] .

If you are interested in adding this new function to your own classes (called subscriptip), you can implement several methods:

 @interface NSArray(Subscripting) - (id)objectAtIndexedSubscript:(NSUInteger)index; @end @interface NSMutableArray(Subscripting) - (void)setObject:(id)obj atIndexedSubscript:(NSUInteger)index; @end @interface NSDictionary(Subscripting) - (id)objectForKeyedSubscript:(id)key; @end @interface NSMutableDictionary(Subscripting) - (void)setObject:(id)obj forKeyedSubscript:(id <NSCopying>)key; @end 

If you implement any of these methods on your own classes, you can index them. Also you can add this feature in OS X 10.7 too!

+13
source

See β€œModern Objective-C,” introduced in iOS 6.

Watch the WWDC 2012 video: Transition to the modern Objective-C .

So, no, the function is not entirely new, and you did not notice it ...; -)

0
source

All Articles