MultiDimensional Array in Objective c
EveryBody..
i want to create one 8*8 dimensional array in objective c..
(
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0开发者_如何转开发, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
[0, 0, 0, 0, 0, 0, 0, 0],
)
like that.. And also use as one of the object can moved in it.. Like want to move
MOVE_ARRAY = array([0, 0], [0, 2])
And also check the array's any position like 5*6 or 4*3 any.. So, Can any one help me about how to initialize , and how to use in code ? Thanks.
In Objective-C:
array = [[NSMutableArray alloc] init];
for (int i = 0; i < 8; i++) {
NSMutableArray *subArray = [[NSMutableArray alloc] init];
for (int j = 0; j < 8; j++) {
[subArray addObject:[NSNumber numberWithInt:0]];
}
[array addObject:subArray];
[subArray release];
}
(array
is an instance variable, that has to be added to your header file and released in you dealloc
method)
To retrieve a value at a certain position you could write a method like this:
- (int)valueAtRow:(int)row andColumn:(int)col {
NSMutableArray *subArray = [array objectAtIndex:row];
return [[subArray objectAtIndex:col] intValue];
}
=== UPDATE ===
To remove an object you could do this:
- (void)removeObjectAtRow:(int)row andColumn:(int)col {
NSMutableArray *subArray = [array objectAtIndex:row];
[subArray removeObjectAtIndex:col];
}
You have to be careful though, because removing objects will change the structure of the array (e.g. the row where you removed an object will have only 7 items after the removal. So you might want to think about leaving the structure intact and set the values that you want to delete to a value that you normally don't use:
- (void)removeObjectAtRow:(int)row andColumn:(int)col {
NSMutableArray *subArray = [array objectAtIndex:row];
[subArray replaceObjectAtIndex:col withObject:[NSNumber numberWithInt:-999]];
}
In C:
int **array = (int**)calloc(8, sizeof(int*));
for (int i=0; i<8; i++) array[i] = (int*)calloc(8, sizeof(int));
// use your array
// cleaning:
for (int i=0; i<8; i++) free(array[i]);
free(array);
To create a constant 2d array containing integers,simply do something like:
NSArray *array;
array = @[@[@1, @7, @4, @11],@[@2, @6, @9]];
This creates an array
1 7 4 11
2 6 9
精彩评论