2

我正在尝试在函数中使用以下代码来返回字典对象数组。不幸的是,在返回堆栈中的下一个函数后,可变数组中的所有行都“超出范围”。根据我的理解,数组应该自动保留行(字典)对象,所以即使在返回之后,行指针超出范围,行对象的保留计数仍然应该为 1。我在这里做错了什么?如何构建此数组以使其包含的对象不会被释放?

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;
4

2 回答 2

1

这一行:

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

应该使用自动释放:

NSMutableDictionary* row = [[[NSMutableDictionary alloc] initWithCapacity:nColumns] ] autorelease];
于 2010-11-18T21:25:10.543 回答
0

据我了解:

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

您应该查看 callMethod 中的局部变量,而不是我调用 getArrayOfDictionaries 的方法本地的 dataTable

于 2010-08-28T20:07:38.597 回答