我认为您正在寻找的解决方案是更有效地使用类。我现在有一个游戏,玩家必须管理在 4 个“走廊”中进行的活动,每个走廊由 3 个“行”组成,每行包含各种坏人、好人等等。您通过滑动循环穿过走廊,每次只能看到 1 个走廊,因此每个走廊都是自己的 hudlayer。管理散落在走廊上的大量坏人是一场噩梦,而且效率非常低,所以我需要一种很好的方法来将坏人分成几组,而无需在 main 函数中使用一堆硬编码的数组......这就是我的方法做到了:
在“self”里面有 4 个大厅 hud 层,每个大厅里面有 3 行是 NSMutableArrays,每行里面是一些代表演员类型(好人、坏人、碎片等)的数组。
将所有这些都放在嵌套数组中是可行的。示例:
NSMutableArray *badGuys;
NSMutableArray *goodGuys;
NSMutableArray *row1 = [NSMutableArray arrayWithObjects: badGuys, goodGuys];
(repeat for row2, row3)
NSMutableArray *hallWay1 = [NSMutableArray arrayWithObjects: row1, row2, row3];
NSMutableArray *mainGame = [NSMutableArray arrayWithObjects: hallway1, hallway2....
但是,这需要大量明确定义的变量。一个更简洁的方法是使用类。
RowClass.h/RowClass.m
在 .h 中:
NSMutableArray *myGoodGuys;
NSMutableArray *myBadGuys;
然后在 .m 中制作
-(NSMutableArray *) returnMyGoodGuys { return myGoodGuys };
HallwayClass.h/HallwayClass.m
RowClass *myRow1 = [[RowClass init] alloc];
RowClass *myRow2 = [[RowClass init] alloc];
RowClass *myRow3 = [[RowClass init] alloc];
NSMutableArray *allMyRows = [NSMutableArray arrayWithObjects: myRow1, myRow2, myRow3];
在.m中:
- (NSMutableArray *) getRowNumber : (int)rowNumber { return allMyRows[rowNumber-1]; }
HallwayClass *hall1 = [[HallwayClass init] alloc];
那么当你需要在某个走廊拉出好人时
NSMutableArray *hall1row1GoodGuys = [[hall1 getRowNumber:1] returnMyGoodGuys];
对数组做点什么
[hall1row1GoodGuys retain];
或者,如果您想在 foreach 循环中处理它:
foreach(RowClass *row in hallway1.allMyRows)
{
do stuff
}
或
for(i=0; i<4; i++)
{
RowClass *nextRow = hallway1.allMyRows[i];
stuff
}
定义类最让我感到害怕,但如果你不去想它,它们实际上很容易使用,并且在组织东西方面做得很好。
希望您能从中获得一些想法:3