user1861458
user1861458

Reputation:

NSDictionary dictionaryWithObjectsAndKeys vs literal notation

What are the differences between using NSDictionary/NSArray constructors and the literal notation?

NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"bar", @"foo"];
NSDictionary *dict2 = @{ @"foo" : @"bar" };

NSArray *arr1 = [NSArray arrayWithObject:@"one", @"two"];
NSArray *arr2 = @[ @"one", @"two" ];

What about accessing dictionary and array elements?

NSLog(@"%@", [dict1 objectForKey:@"foo"]);
NSLog(@"%@", dict2[@"foo"]);

NSLog(@"%@", [arr1 objectAtIndex:0]);
NSLog(@"%@", arr2[0]);

Is the difference purely readability, or is there a performance/behavior difference as well?

Upvotes: 1

Views: 760

Answers (1)

jtbandes
jtbandes

Reputation: 118681

As explained in the Clang documentation, the literal @{} and @[] forms are identical to dictionaryWithObjects:forKeys:count: and arrayWithObjects:count:, which verify that no nil values are present.

Similarly, the subscript notations translate directly to objectAtIndexedSubscript:/setObject:atIndexedSubscript: and objectForKeyedSubscript:/setObject:forKeyedSubscript: (which can be implemented for your own classes if you so desire).

Compiling this code…

@import Foundation;
int main() {
    NSDictionary *dict1 = [NSDictionary dictionaryWithObjectsAndKeys:@"bar", @"foo", nil];
    NSDictionary *dict2 = @{@"foo" : @"bar"};
    NSString *result1 = dict2[@"bar"];

    NSArray *arr1 = [NSArray arrayWithObjects:@"one", @"two", nil];
    NSArray *arr2 = @[@"one", @"two"];
    NSString *result2 = arr2[1];
    return 0;
}

…and opening the binary with Hopper reveals this pseudocode, which is not perfect, but good enough to see what's going on:

pseudocode

Upvotes: 2

Related Questions