2010-08-28 60 views
2

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

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; 
+0

请重新格式化该代码(用于可读性)并告诉我们如何创建和维护dataTable。 – 2010-08-28 09:09:31

+0

为什么你的意思是“超出范围”?为什么你用这种奇怪的方式使用NSMutableDictionary? – unbeli 2010-08-28 09:15:58

+3

dataTable是如何声明/定义的? – 2010-08-28 09:22:02

回答

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中的局部变量,它是本地的我叫getArrayOfDictionaries

1

这条线的方法:

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

应该使用autorelease:

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