从NSObject类获取NSMutableArray到UIViewController类时的MemoryManagement

时间:2011-05-11 14:14:14

标签: iphone objective-c ios memory-leaks

我遇到以下代码泄漏内存的问题......

@property (nonatomic, retain) NSMutableArray *childrensArray;


-(void)connectionDidFinishLoading:(NSURLConnection *)connection {

NSLog(@"Connection finished loading.");  
// Dismiss the network indicator when connection finished loading
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;

// Parse the responseData of json objects retrieved from the service
SBJSON *parser = [[SBJSON alloc] init];

NSString *jsonString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
NSDictionary *jsonData = [parser objectWithString:jsonString error:nil];
childrensArray = [jsonData objectForKey:@"Children"];

// Callback to AttendanceReportViewController that the responseData finished loading
[attendanceReportViewController loadChildren];

[connection release];
[responseData release];
[jsonString release];
[parser release]; 
}  

在viewController中,以下内容也会泄漏内存......

@property (nonatomic, retain) NSMutableArray *childrensArray;


- (void)loadChildren {

// Retrieve a array with dictionaries of children from ServiceGetChildren
self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease];   

int total = [childrensArray count];
totalLabel.text = [NSString stringWithFormat:@"%d", total]; 

[theTableView reloadData];
}   

1 个答案:

答案 0 :(得分:1)

只有在取消分配实例时才释放childrensArray。您还应该在设置之前释放实例变量:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    [childrensArray release];
    childrensArray = [serviceGetChildren.childrensArray copy]; 
}

更好的方法是实际使用您的财产:

- (void)loadChildren {
    // Retrieve a array with dictionaries of children from ServiceGetChildren 
    self.childrensArray = [[serviceGetChildren.childrensArray copy] autorelease]; 
}

(注意autorelease

如果您使用KVO通知,这有助于触发KVO通知。