Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSArray objectAtIndex: shorthand [duplicate]

Tags:

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!!

like image 801
George Green Avatar asked Feb 05 '13 13:02

George Green


People also ask

Can NSArray contain nil?

arrays can't contain nil.

What is NSArray?

NSArray creates static arrays, and NSMutableArray creates dynamic arrays. You can use arrays when you need an ordered collection of objects. NSArray is “toll-free bridged” with its Core Foundation counterpart, CFArrayRef . See Toll-Free Bridging for more information on toll-free bridging.

Is NSArray ordered?

The answer is yes, the order of the elements of an array will be maintained - because an array is an ordered collection of items, just like a string is an ordered sequence of characters...


1 Answers

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).

like image 111
Adam Wright Avatar answered Nov 16 '22 21:11

Adam Wright