返回指针后,NSArray对象超出范围

时间:2010-08-28 09:05:26

标签: iphone objective-c database memory retain

我试图在函数中使用下面的代码来返回一个字典对象数组。不幸的是,在返回堆栈中的下一个函数之后,可变数组中的所有行都变得“超出范围”。根据我的理解,数组应该自动保留行(字典)对象,因此即使在返回之后,行指针超出范围,行对象仍应保留计数为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;

2 个答案:

答案 0 :(得分:1)

这一行:

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

应该使用autorelease:

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

答案 1 :(得分: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];
}

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