views:

232

answers:

2

I have a collection of NSObjects that I want to store in a 2D array generated at run time. In C# I'd just be using some of their friendly generic containers, but not too sure the best way to go about it in objective-c for iphone development.

I'm guessing that NSMutableArray isn't the best route. I don't need the array to grow, I'll know the size I want when my grid manager is created, but the grid will be constructing with a runtime height and width.

Should I be doing something along the lines of 'NSObject** gridObjects = alloc...'?

+3  A: 

If you are going to store POINTERS in your 2D array, you will have to use:

NSObject ***gridObjects

I would just use a NSArray of NSArray objects (2D).

Pablo Santa Cruz
A: 

You can always use plain C stuff in Objective-C (I wouldn't suggest doing this unless you have good reasons to):

NSObject** *twoDArray = malloc(sizeof(NSObject**) * rows);
for (i = 0; i < rows; ++i)
    twoDArray[i] = malloc(sizeof(NSObject*) * cols);

To resize each block, you can use realloc (if you even needed). Don't forget to free after use.

Mehrdad Afshari
That works, and I have it as a property of my class, but I'm having trouble assigning values. I created it with a Tile type.Tile* tile = [[Tile alloc] init];self.grid[x][y] = tile; I have the error "Incompat types in assignment"
Mr Snuffle
Ah, figured it out. Needed tile Tile***
Mr Snuffle
Be careful with this solution, as it is incompatible with garbage collection. Could use NSAllocateCollectable to get around this, but I'd also recommend an NSArray of NSArrays.It might be nice to write a category method to access elements here.
Joey Hagedorn