views:

1972

answers:

3

I have a two-dimensional C array of Objective-C objects. How do I access the members of those objects?

id array[5][5];
array[0][0] = [[Ball alloc] init];

The Ball class has two members:

int size;
CGPoint point;

How can I access size for the Ball object stored in array[0][0]? Please tell me how I can do this.

Thanks in advance!

+1  A: 

Depending on which runtime (32-bit or 64-bit) and whether you declare the instance variables (size and point) explicitly or have them synthesized by the runtime, you may be able to access them directly as in array[0][0]->size. This is not a good idea however. It will break on modern runtimes and is very much not the Objective-C way and breaks encapsulation by publicly exposing implementation details of the class.

In Objective-C 2.0, the correct practice is to declare a property for each attribute that you want to be puclically visible. Add the following to Ball's @interface declaration:

@property (assign) int size;
@property (assign) CGPoint point;

And in the @implementation block of Ball:

@synthesize size;
@synthesize point;

You can now access size like ((Ball*)array[0][0]).size. The cast is required for the compiler to recognize the dot notation as a property access. It is not required if you use the accessor methods (which are automatically generated by @synthesize): [array[0][0] size].

Barry Wark
+1  A: 

While it may not be completely relevant to your question (and maybe you're just using a simplified example), but why not use use structs instead of objects in this case? As both size and point are non-objects, it might make more sense.

jbrennan
A: 

You could do it like this:

@interface Moo : NSObject {
@public
    int age;
}

And then you can do this without warning:

Moo *m = [[Moo alloc] init];
m->age = 16;
Moo *arr[4];
arr[0] = m;
printf("Age: %d",arr[0]->age);

You could also do some casting:

id arr[4];
arr[0] = m;
printf("Age: %d",((Moo *)arr[0])->age);

This should work with any number of dimensions of arrays! Hope this helps.

micmoo
Publicly exposing instance variables is NOT a good way to accomplish this in Objective-C. It makes for fragile code. I suggest Barry's solution above.
Quinn Taylor
All he asked was how to do it.
micmoo