Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing keys in NSDictionary using [key] notation?

I have just realised 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 anyone tell me if this has been hiding from me all along or if its some fairly recent change to the language?

EDIT: The question does not generically refer to the new string literals, but more specifically to accessing NSDictionary with the same string literal syntax you would use for NSArray. I obviously overlooked this and just wanted to check when this particular syntax was added.

like image 313
fuzzygoat Avatar asked Feb 14 '13 15:02

fuzzygoat


People also ask

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.

What is NSDictionary in Objective c?

The NSDictionary class declares the programmatic interface to objects that manage immutable associations of keys and values. For example, an interactive form could be represented as a dictionary, with the field names as keys, corresponding to user-entered values.

What is NSMutableDictionary in Swift?

The NSMutableDictionary class declares the programmatic interface to objects that manage mutable associations of keys and values. It adds modification operations to the basic operations it inherits from NSDictionary . NSMutableDictionary is “toll-free bridged” with its Core Foundation counterpart, CFMutableDictionary .

How do you add value in NSMutableDictionary?

[myDictionary setObject:nextValue forKey:myWord]; You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).


1 Answers

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

If you're interested in adding this new feature to your own classes (called subscripting), there's a few methods you can implement:

@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 subscript on them. This is also how you can add this feature to OS X 10.7 too!

like image 169
Aditya Vaidyam Avatar answered Sep 30 '22 15:09

Aditya Vaidyam