Search code examples
objective-ccocoansarrayobjective-c-literals

Special way of representing array in objective-c


I have seen in many places over the net and even in apple documentation when an array is represented in the following format:

@[obj1,obj2]

For eg; In predicate programming guide there is a statement like this:

NSCompoundPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:@[greaterThanPredicate, lessThanPredicate]];

But when I write the same in code , i get an 'unexpected @ in program' (as expected) compiler error. Is this just a way of representing arrays or am i missing something?


Solution

  • This is a relatively new syntax, it is available only with Xcode that includes clang 3.3 or newer.

    This

    @[greaterThanPredicate, lessThanPredicate]
    

    is logically equivalent* to this:

    [NSArray arrayWithObjects:greaterThanPredicate, lessThanPredicate, nil]
    

    You can always replace the new syntax with the old one without losing functionality.

    EDIT (in response to a comment by Nikolai Ruhe) Apple has a different version scheme than the open source version. The correct version numbers that introduced the feature are: Apple 4.0, clang 3.1.


    * Under the hood the array initializer of the new syntax is transformed to a call of arrayWithObjects:count:. Thanks to newacct for the correction.