Bordz
Bordz

Reputation: 2810

dictionary[@"myKey"] VS [dictionary valueForKey:@"myKey"]

Im just wondering whats the difference between the two, which one is faster and their pros and cons.

Upvotes: 2

Views: 660

Answers (4)

Duncan C
Duncan C

Reputation: 131418

As others have said, you should not compare

dictionary[@"key"]

with [dictionary valueForKey: @"key"]

The second valueForKey method uses key-value coding (KVC) which is very different.

dictionary[@"key"] is functionally equivalent to [dictionary objectForKey: @"key"] The results are the same, even though dictionary[@"key"] calls a slightly different method.

The first dictionary[@"key"]form uses new "object literal" syntax which is a recent addition to the Objective-C language.

Upvotes: 0

rmaddy
rmaddy

Reputation: 318804

The syntax dictionary[@"myKey"] is the same as calling [dictionary objectForKeyedSubscript:@"myKey"] which is basically the same as calling [dictionary objectForKey:@"myKey"].

The method valueForKey: is used for KVC (Key-value coding). If the key doesn't start with @ then it will end up giving the same result at objectForKey: but if the key starts with @, the result will be quite different.

Upvotes: 2

Bryan Chen
Bryan Chen

Reputation: 46598

dictionary[@"myKey"]

is translated to

[dictionary objectForKeyedSubscript:key]

by compiler which is equivalent to

[dictionary objectForKey:key]

and

dictionary[@"myKey"] = value

is translated to

[dictionary setObject:newValue forKeyedSubscript:key]

which is equivalent to

[dictionary setObject:newValue forKeye:key]

doc from clang

Upvotes: 1

drewag
drewag

Reputation: 94723

-valueForKey is a method that can be called on any object to get the value of a property named the given "key". It will not give the value in the dictionary for the object at the given dictionary key.

If however, you meant to ask about -objectForKey then dictionary[@"myKey"] is just a shorthand for [dictionary objectForKey:@“myKey”]. They both compile into the same thing.

Upvotes: 0

Related Questions