简体   繁体   English

可变数组的二维NSMutableArray,但不知道我需要多少

[英]Two-dimensional NSMutableArray of mutable arrays, but don't know how many I'll need

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. 我以为使用二维NSMutableArray是可以的,但是如果我按如下所示进行操作,那么当我清空tempArray时,它也会清空fullArray中的数组。 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
}

}

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. 我尝试使用C数组,但无法以这种方式创建全局数组。 I tried defining a global array and using "new" in create array, but Xcode says "new" is unrecognized. 我尝试定义一个全局数组并在create array中使用“ new”,但是Xcode表示“ new”无法识别。 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? 也许我要解决所有这些错误?

Thanks for any help. 谢谢你的帮助。

Change just about 2 lines and you've got it. 更改大约2行就可以了。

- (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
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM