PTTHomps
PTTHomps

Reputation: 1499

What does this Objective-C code snippet mean, and what document details it?

Ok, so I've done searches in Xcode, on Apple's developer's site, and on google, and have even downloaded and searched pdf versions of the Key-Value Coding Programming Guide and Collections Programming Topics, but I cannot find this syntax listed anywhere. What does the second line of the following snippet do, and where can I find the details on it?

NSMutableDictionary *change = [NSMutableDictionary new];
change[@(someVariable)] = @(someOtherVariable);

I don't know if I'm having a brain fart, or if I've actually never seen this before, but it really bugs me that I can't find documentation for it.

Upvotes: 1

Views: 196

Answers (3)

matt
matt

Reputation: 535139

There are actually two things going on here:

  1. Dictionary (and array) subscripting

    change[key]
    

    This is a new syntactic sugar for

    [change objectForKey:key]
    

    Or, if used as an lvalue, it is syntactic sugar for

    [change setObject:value forKey:key]
    

    For what's really going on here (objectForKeyedSubscript: and setObject:forKeyedSubscript:) see http://www.apeth.com/iOSBook/ch10.html#_nsdictionary_and_nsmutabledictionary

  2. Number literals

    @(someVariable)
    

    This is a new compiler directive, equivalent to:

    [NSNumber numberWithInt: someVariable]
    

    Except that in fact it will use numberWithInt:, numberWithFloat:, or whatever is appropriate based on the type of someVariable.

    Again, see http://www.apeth.com/iOSBook/ch10.html#_nsnumber

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726559

This is the new syntax introduced in Objective C relatively recently. It is documented at this link.

Scroll down to Object Subscripting syntax for an explanation:

Objective-C object pointer values can now be used with C’s subscripting operator.

Your code fragment translates as

[change setObject:@(someOtherVariable) forKeyedSubscript:@(someVariable)];

To support the new syntax described there, the Objective-C @-expression grammar has been introduced. The @-expression is explained at the bottom of the document.

Upvotes: 3

Stavash
Stavash

Reputation: 14304

http://clang.llvm.org/docs/ObjectiveCLiterals.html

Check out "examples" about half way through the doc

Upvotes: 1

Related Questions