views:

83

answers:

3

Hi guys, I have a variable declared like this in a class:

Entity *array[BOARD_SIZE][BOARD_SIZE];

I need to set up either a @property that allows me to access (read) the array elements, or a function that returns a reference so I can access the array elements.

-  ( ??? ) getEntityArray
{
   return ???;
}

or

@property (????) Entity ??? ;

I really need to work with the array declared in this way.

Any advice?

Thanks!

+4  A: 

Don't do this. Use an NSArray to store Objective-C objects.

Have a look at the answer to this question if you want to know how to handle multi-dimensional arrays of primitives:

http://stackoverflow.com/questions/1382417

Rob Keniger
A: 

You could do one of the following - use a typedef to make it easier to handle or not.

in your .h file:

#define BOARD_SIZE 32
typedef NSString *EntityArrayPtr[BOARD_SIZE][BOARD_SIZE];

@interface EntityTestWithNSString : NSObject {
    EntityArrayPtr *x;
    NSString *tempStrs[15][15];
}

@property NSString **tempStrs;
@end

in your .m file:

-  ( EntityArrayPtr *) getEntityArray
{
    return x;
}

- (NSString **) getStringArrays
{
    return &tempStrs[0][0];
}

I just compiled this and it compiles. I'll leave it to you to see which works best for your situation.

You could make methods that grab you the one entity at the index1.index2 that you need...

I definitely would make methods to return to you exactly the object you need, instead of handing off an array pointer and letting some other object mess around with it.

mahboudz
This doesn't compile (even when changing the return statement to "return x" and declaring a variable x of type EntityArrayPtr
Philippe Leybaert
Does so! :-) See edited answer
mahboudz
One other question to ask is whether the storage allocated for the entire EntityArray should reside amongst the instance vars, or whether there should just be a pointer there to storage that is malloced later for the array to use.
mahboudz
A: 

While Rob's answer is valid, the question itself is interesting. Objective C is just a layer on top of standard C, so a question about returning array types is valid.

The answer to the question is pretty easy: it's not possible to return array types in C. You can only return pointers. The problem with returning a pointer is that the dimensions of the multidimensional array are unknown to the caller, so you can't use the returned value as a multidimensional array.

Philippe Leybaert