0

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
}

}

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?

Thanks for any help.

1

1 Answer 1

1

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
    }

}
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.