可变数组的二维NSMutableArray,但不知道我需要多少 [英] Two-dimensional NSMutableArray of mutable arrays, but don't know how many I'll need
问题描述
我有一个大数组(几百个对象),我需要根据对象中的整数将其分成几个数组,但是我不知道我需要多少个数组。我以为使用二维NSMutableArray是可以的,但是如果我按如下所示进行操作,那么当我清空tempArray时,它也会清空fullArray中的数组。还有另一种使用临时可重复使用的数组的方法,一旦将其添加到另一个数组中,它就会释放对其的引用。
I have a large array (a few hundred objects), and I need to separate it into several arrays depending on an integer in the object, but I don't know how many arrays I'll need. I thought using a two-dimensional NSMutableArray would work, but if I do it as seen below, then when I empty the tempArray, it empties the array in fullArray as well. Is there another way to use a temporary, reusable array that, once it's been added to another array, it releases references to it.
- (void)createArray{
fullArray=[[NSMutableArray alloc]init];
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for(int j=0; j<numberOfGames; j++){
for(int i=0; i<[appDelegate.hiddenChars count]; i++){
Chars *charObj=[appDelegate.hiddenChars objectAtIndex:i];
if(charObj.gameID==j){
//NSLog(@"Match!");
[tempArray addObject:charObj];
}
}
[fullArray addObject:tempArray];
[tempArray removeAllObjects]; //this empties it from fullArray too
}
}
我可以获取多少行和列的变量,但它们不是静态的。我曾尝试使用C数组,但无法以这种方式创建全局数组。我尝试定义一个全局数组并在create array中使用 new,但是Xcode表示 new无法识别。
我尝试过
I can get a variable for how many rows and columns, but they're not static. I've tried using C arrays, but I won't be able to make a global array that way. I tried defining a global array and using "new" in create array, but Xcode says "new" is unrecognized. I tried
id fullArray;//in global scope
fullArray=new id fullArray[rows][columns];//new and id throw exceptions, new unrecognized and id expects ";" before it.
我的另一种想法是创建一个单例,但是对于这个问题似乎有点过头了。当然,有一种方法可以处理需要数量未知的数组吗?
My other thought is to create a singleton, but it seems like overkill for this problem. Surely there's a way to handle needing an unknown number of arrays?
我将使用这些数组来填充具有多个部分的分组表格视图。
I'll be using the arrays to populate a grouped tableview with multiple sections. Maybe I'm going about this all wrong?
谢谢您的帮助。
推荐答案
更改大约2行就可以了。
Change just about 2 lines and you've got it.
- (void)createArray{
fullArray=[[NSMutableArray alloc]init];
for(int j=0; j<numberOfGames; j++){
// inside loop
NSMutableArray *tempArray=[[NSMutableArray alloc] init];
for(int i=0; i<[appDelegate.hiddenChars count]; i++){
Chars *charObj=[appDelegate.hiddenChars objectAtIndex:i];
if(charObj.gameID==j){
//NSLog(@"Match!");
[tempArray addObject:charObj];
}
}
[fullArray addObject:tempArray];
[tempArray release]; // but fullArray still owns it
}
}
这篇关于可变数组的二维NSMutableArray,但不知道我需要多少的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!