Setting a Value in NSDictionary

suggest change

There are multiple ways to set an object for a key in an NSMutableDictionary. NSDictionary itself cannot be changed. For instance, to add a Lamborghini to a list of cars:

Standard

[cars setObject:lamborghini forKey:@"Lamborghini"];

setObject:forKey: is the NSMutableDictionary method that sets an object for a key. Do not confuse it with setValue:forKey:, which is Key-Value Coding. objectForKey: reads a value; it does not set one.

Shorthand

cars[@"Lamborghini"] = lamborghini;

Subscript assignment is standard Objective-C since Xcode 4.4. On a mutable dictionary it calls setObject:forKeyedSubscript:.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents