2011-05-11 63 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