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

getArrayOfDictionaries と呼んだメソッドにローカルな dataTable の代わりに、callingMethod のローカル変数を調べる必要があります。

于 2010-08-28T20:07:38.597 に答える