Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDictionary access values shortcut

I don't understand the differences between these ways of accessing NSDictionary values

[my_dict objectForKey:@"field"]
[my_dict valueForKey:@"field"]
my_dict[@"field"]

Can someone tell me ?

like image 665
Pierre de LESPINAY Avatar asked Jan 16 '13 16:01

Pierre de LESPINAY


People also ask

What is NSDictionary in Objective c?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.

How do you add value in NSMutableDictionary?

You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil). The simplified form mentioned above, usually solves problems OCLint (metric static code analysis).

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 ID in Obj C?

id is a data type of object identifiers in Objective-C, which can be use for an object of any type no matter what class does it have. id is the final super type of all objects.

What is a key and value in a dictionary?

In general, a key can be any object (provided that it conforms to the NSCopying protocol—see below), but note that when using key-value coding the key must be a string (see Accessing Object Properties ). Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull.

Can a key or value be nil in NSDictionary?

Neither a key nor a value can be nil; if you need to represent a null value in a dictionary, you should use NSNull. NSDictionary is “toll-free bridged” with its Core Foundation counterpart, CFDictionary. See Toll-Free Bridging for more information on toll-free bridging.

Which dictionary provides mapping from keys to values?

Dictionary that provides mapping from keys to values. Foundation. NSDictionary<TKey,TValue> Foundation. NSMutable Dictionary

What does the NSDictionary dictionary key return?

Returns the value associated from a key in the dictionary, or null if the key is not found. Returns the value associated from a key in the dictionary, or null if the key is not found. The set of keys for the NSDictionary.


1 Answers

[my_dict objectForKey:@"field"] is an NSDictionary method. It accepts any type of object.

[my_dict valueForKey:@"field"] is KVC method. It accepts only NSString.

my_dict[@"field"] is same as objectForKey:. This is new feature added.

like image 71
Anoop Vaidya Avatar answered Sep 19 '22 15:09

Anoop Vaidya