0

As far as my study is concern for Objective C, I found this code for displaying the array elements:

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:@"a", @"b", @"c"];
int x = 0;

for(; x<[myArray count]; x++)
    NSLog(@"value at index %i is %@", x, [myArray objectAtIndex:x]);

I am just curious if this is possible below: using [myArray[x]] instead of [myArray objectAtIndex:x] instead

for(; x < [myArray count]; x++)
    NSLog(@"value at index %i is %@", x, [myArray[x]]);
1
  • 1
    By the way, my book might help you: much of the emphasis of its early chapters is on Objective-C, the language. Here's the chapter on syntax: apeth.com/iOSBook/ch03.html Commented Dec 27, 2011 at 2:18

2 Answers 2

1

No, it isn't. An NSArray is not a C array; it's an object like any other object and you have to talk to it the way you'd talk to any other object, using full-fledged message syntax. (The only "shortcut" of the sort you're looking for is properties.) I'm sorry, but Objective-C is horribly verbose, and this is an excellent case in point. You'll become accustomed to using code completion as much as possible, to avoid typing all those letters...

Sign up to request clarification or add additional context in comments.

Comments

1

You cannot, and the reason is fairly simple: Objective-C is based on C and retains backwards compatibility.

In C, using [i] on an object will call the [] operator of that object. However, on the local scope all Objective-C objects are simply pointers, which would make the call something similar to int[3]. Does that look valid to you?

Implementing [] for NSArray would mean breaking backwards compatibility.

6 Comments

I believe Objective-C is based on C, not on C++ (but the point is probably the same).
Hey, that's interesting. I've been programming heavily in Objective-C for almost two years now, and I never realized it's based on C. It mixes really well with C++ :-) Updated my answer.
That's because C++ is very nearly a superset of C, which makes Objective-C look like it could be an extension of a subset of C++. But in fact, it was based on C, and was developed around the same time that C++ was. The add-on stuff is based on Smalltalk.
@TomvanderWoerdt - Objective-C++ is actually a different language. That may be what you've been using...
@TomvanderWoerdt cool - I'm just saying that if you really love C++ and want the benefits of using it, you can: there is a standard iOS Objective-C++. Change the source file suffix from .m to .mm and presto, you're there. And ARC continues to work.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.