问题描述
EveryBody ..
EveryBody..
我想在目标c中创建一个8 * 8维数组。
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])
并检查阵列的任何位置,如5 * 6或4 * 3任何..
所以,任何人都可以帮助我如何初始化,以及如何在代码中使用?
谢谢。
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.
推荐答案
在Objective-C中:
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
是一个实例变量,必须添加到头文件并在您的 dealloc
方法中释放
(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];
}
===更新===
要删除一个对象,你可以这样做:
To remove an object you could do this:
- (void)removeObjectAtRow:(int)row andColumn:(int)col {
NSMutableArray *subArray = [array objectAtIndex:row];
[subArray removeObjectAtIndex:col];
}
你必须要小心,因为删除对象会改变结构数组(例如,删除对象的行在删除后只有7个项目。因此,您可能需要考虑保留结构的完整性,并将要删除的值设置为通常不使用的值:
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]];
}
这篇关于目标c中的多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!