Is it possible to access NSArray's objects using [idx]? I have a standard library that uses [] style indexing and I don't want to rewrite the whole library to suit ObjC's objectAtIndex: method.
As in, NSArray *obj = [NSArray ...]; id item = obj[0];
The accepted answer (whilst true at the time) is now out of date. As of Xcode 4.5, you can now set and get NSArray elements using:
You can also do the same for NSDictionaries using:
Even cooler, you can now create array and dictionary objects using JSON-like syntax:
And in a similar vein, boxed values like NSNumber can now be written in a shorthand syntax:
EDIT:
Far more detailed answer than mine here: What are the details of "Objective-C Literals" mentioned in the Xcode 4.4 release notes?
EDIT 2:
To be clear, though this feature wasn't added until Xcode 4.5, it works on iOS 4.3 and above, so you don't have to avoid using this if you need to support older iOS versions.
EDIT 3:
For the sake of pedantic precision, it works on Apple LLVM compiler version 4.1 and above. AKA the version that shipped with Xcode 4.5.
It is not possible, unfortunately (or not). The only option you have is to build a C++ wrapper around
NSArray
and overrideoperator[]
. Then, all of your files that use that wrapper should be Objective-C++ (i.e., use the .mm extension) to be correctly compiled.EDIT:
An update to this answer. As of Xcode 4.5/iOS 6, it is possible to user subscript notation to access an NSArray elements:
This is the official Xcode 4.5 release notes wording:
(Thanks to Nick Lockwood for his comment below)
Nope. You can, however, extract the NSArray's contents into a C array and then use the subscript operator with that.