NSArray objectAtIndex: shorthand [duplicate]
Asked Answered
T

4

25

Possible Duplicate:
Is there some literal dictionary or array syntax in Objective-C?

I have recently noticed that something strange seems to work in objective-c.

When I have an array,

NSArray *myArray = @[@"1", @"b", @"3", @"d"];

I can normally access the second element by,

NSString *element = [myArray objectAtIndex:1]; // second element 

however I seem to now also be able to access it via.

NSString *element = myArray[1];

Does anyone know if this is now a defined behaviour and therefore safe to use, or should I avoid it? Thanks to anyone who can help!!

Therefor answered 5/2, 2013 at 13:45 Comment(2)
Sorry, wasn't quite sure how to search for it.Therefor
Thanks everyone for your answers!! :)Therefor
C
29

This syntax was added in Clang 3.3 : Objective C Literals. Essentially, the compiler converts expressions of the type objCObj[idx] to the expression [objCObj objectAtIndexedSubscript:idx]. It also works for dictionaries, and you're free to adopt it for your own objects.

As such, you're perfectly safe using it, assuming you'll be using a modern version of Objective C and suitably updated Objective C compiler (i.e. Clang).

Cartercarteret answered 5/2, 2013 at 13:48 Comment(1)
Apple has made a mess out of shorthand.. What happened to "if it's not broken, don't fix it" ?Derm
H
4

this is a new feature of objective-c and avaiable since xCode 4.5

its safe to use this syntax, you can even give your own classes support for this.

Helaina answered 5/2, 2013 at 13:48 Comment(0)
T
2

Ya, it's safe to use these syntax.

Those syntax are part of Modern Objective-C.

You can check this article for more options: ObjectiveCLiterals

Tass answered 5/2, 2013 at 13:51 Comment(0)
M
2

It's a perfectly valid code for the latest version of the LLVM compiler. So far, it's invalid for other compilers (e.g. GCC).

Whether you should avoid it or not - well, it's a matter of taste. There are several big discussions about it on the internet since the indexing behaves slightly different (a whole different method is used to implement it). There are also discussions whether to use the expression literals or not since there are ocassions when they are making the code less readable (e.g. they are written like literals but they actually are autoreleased objects). Note that everything is done using literals can be done using simple macros.

Must answered 5/2, 2013 at 13:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.