views:

111

answers:

1

I am attempting to use the below code in a function to return an array of dictionary objects. Unfortunately, after the return to the next function in the stack all of the rows in the mutable array have become 'out of scope'. From my understanding, the array should retain the row (dictionary) object automatically so even after the return, where the row pointer goes out of scope, the row objects should still have a retain count of 1. What am I doing wrong here? How do I build this array in such a way that the objects it contains don't get released?

for (int i = 1; i < nRows; i++)
{
  NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ];
  for(int j = 0; j < nColumns; j++)
  {
    NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
    NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];

    [row setValue:value forKey:key];
  }
  [dataTable addObject:row];
}

return dataTable;
A: 

From what i understand:

-(NSMutableArray*) getArrayOfDictionaries{
    int nRows=somenumber;
    int nColumns=someOthernumber;
    char **azResult=someArrayOfStrings;

    NSMutableArray *dataTable=[[NSMutableArray alloc] init];
    for (int i = 1; i < nRows; i++)
    {
      NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns]];
      for(int j = 0; j < nColumns; j++)
      {
        NSString* key = [[NSString stringWithUTF8String:azResult[j]] ];
        NSString* value = [[NSString stringWithUTF8String:azResult[(i*nColumns)+j]] ];

        [row setValue:value forKey:key];
      }
      [dataTable addObject:row];
      //you should add the following line to avoid leaking
      [row release];
    }

    //watch for leaks
    return [dataTable autorelease];
    //beyond this point dataTable will be out of scope
}

-(void) callingMethod {
    //dataTable is out of scope here, you should look into arrayOfDictionaries variable
    NSMutableArray* arrayOfDictionaries=[self getArrayOfDictionaries];
}

You should look into the local variable in callingMethod instead of dataTable which is local to the method I called getArrayOfDictionaries

Leg10n