Compiler error "expected method not found" when using subscript on NSArray

Ben Trengrove picture Ben Trengrove · Jul 11, 2012 · Viewed 12k times · Source

I wrote this simple code to try out the new Objective-C literal syntax for NSArrays:

NSArray *array = @[@"foo"];
NSLog(@"%@", array[0]); 

The first line works fine, but the subscripting results in an error:

Expected method to read array element not found on object of type 'NSArray *'

Just wondering if I have done something wrong, or if the literals haven't been fully implemented yet. I'm compiling with Apple LLVM 4.0 and using the iOS 5 SDK.

Here's a screenshot of the error, too.

Error

Answer

jscs picture jscs · Jul 11, 2012

You've got to be compiling with the iOS 6 or OS X 10.8 SDKs -- otherwise Foundation objects don't have the necessary methods for the subscripting bit of the literal syntax.* Specifically in this case, the subscripting expects objectAtIndexedSubscript: to be implemented by NSArray, and that's a new method that was created to interact with this compiler feature. The parts of the new syntax that just have to do with object creation should work fine, though -- I don't believe that requires any new methods.

Further reading at http://clang.llvm.org/docs/ObjectiveCLiterals.html


*I base this on a bit of research performed by borrrden: https://stackoverflow.com/a/11407844/603977

I've gotten a lot of upvotes on this answer, which I really feel is founded on borrrden's. Please, if you think my answer is worth an upvote, click through and vote there too.