开发者

NSArray objects go out of scope after returning pointer

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 beco开发者_如何学JAVAme '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;


This line:

NSMutableDictionary* row = [[NSMutableDictionary alloc] initWithCapacity:nColumns] ];

should use the autorelease:

NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ] autorelease];


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜