2011-05-11 61 views
1

我有下面的代码泄漏内存问题...Memorymanagement得到一个NSMutableArray的时候从NSObject类到UIViewController类

@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

请问您是否可以清理您的帖子的代码。 – toto 2011-05-11 14:27:40

+0

我只是说,但是......在你的一行泄漏之后('childrensArray = [serviceGetChildren.childrensArray copy];''你有'{'而不是}},并且我希望这不是完全的复制粘贴一次,但复制粘贴部分,对吗?因为如果布局是完全一样的,还有更多.. ahum,东西,错误。 – Joetjah 2011-05-11 14:28:46

+0

@toto是的,当然对不起,现在可能更容易阅读 – Silversnail 2011-05-11 14:52:54

回答

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通知。

+0

另一个问题是'childrensArray = [jsonData objectForKey:@“Children”];',它会覆盖childrensArray实例变量而不会释放它,应该使用临时变量来代替 – Tony 2011-05-11 14:30:32

+0

好吧,如果我做self.childrensArray = [ [serviceGetChildren.childrensArray copy] autorelease]; \t 我不需要释放它在dealloc? – Silversnail 2011-05-11 14:31:46

+0

@Tony好吧但如果我使用一个临时变量,如何我可以从viewController中检索它吗?我还是设置它的财产?或者你是什么意思? – Silversnail 2011-05-11 14:34:19