views:

26

answers:

2

Hi, everyone,

I want to ask a question about the objective C. I used to ask how to declare a 2D array in the objective in the past and I get the 2D array. However, I modify some of the code and try to display the content of the array. I found that the input is wrong. Can anyone help me to point out the mistake.

     // Program: convent a 1D array into 2D array and retrieve the element in the array
     // example
     // dataArray[0]=First Name, [1]=Last Name, [2]=Tom, [3]=chan, [4]=May, ...
     // I want to break the array into outerArray, interArray

         NSString *temp;

        outerDataArray = [[NSMutableArray alloc]init];
        innerDataArray = [[NSMutableArray alloc]init];

        for(int i=0; i<[dataArray count]; i++)
        {

            temp = [dataArray objectAtIndex:i];
            [innerDataArray addObject:temp];
            [temp release];

            if(i%[titleArray count] == 0 && i!=0)
            {
                [innerDataArray release];
                innerDataArray = [[NSMutableArray alloc]init];

                [outerDataArray addObject:innerDataArray];
            }
        }

        [innerDataArray release];

        NSMutableArray *tempArray;

        // display
        for(int i=0; i<[outerDataArray count]; i++)
        {
            tempArray = [outerDataArray objectAtIndex:i];

            for(int j=0; j<[innerDataArray count]; j++)
            {
                NSLog(@"%@", [tempArray objectAtIndex:j]);
            }

        }
+1  A: 

It sems you add to this 'innerDataArray' but then when you reach a count you release it directly before you add it to the outerDataArray:

        if(i%[titleArray count] == 0 && i!=0)
        {
            [innerDataArray release];
            innerDataArray = [[NSMutableArray alloc]init];

            [outerDataArray addObject:innerDataArray];
        }

shouldn't it be?

        if(i%[titleArray count] == 0 && i!=0)
        {
            [outerDataArray addObject:innerDataArray];
            [innerDataArray release];
            innerDataArray = [[NSMutableArray alloc]init];

        }
Anders K.
+1  A: 
        [temp release];

In the code shown, you do not retain temp and should not release it.

            [outerDataArray addObject:innerDataArray];

You add an empty innerDataArray, so you are probably dropping the first set of entries. Move this line to before innerDataArray is released or add the first innerDataArray before the loop starts.

drawnonward