Reputation: 465
I am working on an iphone app in objective-c and I am having trouble with making an array out of a class variable, for example...
I have a class named Cube
and I am tryin to make an instance of this class named map that is an array
Cube map[10][10];
Xcode then says it is an error and suggests I do this
Cube *map[10][10];
When I do it this way though ^ I cannot access one of my methods I defined in the class Cube
, now this is not ALL my methods, it is just one single method that wont work anytime I try to call it. The only thing different about this method than the others is that I pass a parameter to it. The Cube
class declaration and definition both compile flawlessly.
Can anyone explain to me how to make a class with a 2 dimensional without turning it into a pointer. Also why does xcode recommend I make it a pointer, and why doesn't the method work when I do it this way?
Upvotes: 0
Views: 101
Reputation: 51
The standard approach for this in Objective-C is to create an NSArray(or NSMutableArray)
of an NSArray
(or NSMutableArray
). Assuming you want to be able to manipulate the array after you create the array object, your code would look something like this:
NSMutableArray* cubeGrid = [NSMutableArray new]; // Note that this code assumes you are using ARC.
// add row 1
NSMutableArray* cubeRow1 = [NSMutableArray arrayWithObjects:cube1,cube2,cube3,nil]; // you will need to add cube 4 to 10 in the real code
[cubeGrid addObject:cubeRow1];
// add row 2
NSMutableArray* cubeRow2 = [NSMutableArray arrayWithObjects:cube11,cube12,cube13,nil]; // you will need to add cube 14 to 20 in the real code
[cubeGrid addObject:cubeRow2];
// and you will create the rest of the rows and add to the cubeGrid array
To access the elements you would do something like this:
for (id cubeRow in cubeGrid) {
if ([cubeRow isKindOfClass:[NSArray class]]) {
for (id cube in (NSArray*)cubeRow) {
if ([cube isKindOfClass:[Cube class]]) {
// Do things with cube
}
}
}
}
What you might also want to double check is whether the method that you are trying to access is declared in the header file.
Upvotes: 2
Reputation: 15853
You probably want to use a Cocoa style array, i.e. NSArray
or NSMutableArray
instead of C-style array. It is much more flexible and is designed to work with Objective-c objects. Have a look at this simple tutorial on using a Cocoa array: http://iphonelearning.wordpress.com/2011/08/24/nsarray-and-nsmutablearray/.
Upvotes: 2