昨天我提出了一個關於內存管理和單例的問題(Proper Management Of A Singleton Data Store In IOS With Web Service)。在過去的36個小時裏,我一直試圖追蹤這個問題,經過NSLog等的廣泛測試之後,我只能斷定塊內分配的對象沒有被自動釋放。我使用塊來處理異步Web服務響應。我還從視圖控制器發送一個需要提供Web服務請求的塊,以便它可以根據Web服務的響應執行任何操作。希望全面瞭解我的代碼有助於獲得解決方案,我將所有產生問題的代碼放在這裏:塊和內存管理
第一步是從我的根視圖控制器發出請求。當它加載時,我要求所有用戶的「Hollers」是我在內部使用的術語,基本上是指事件。當根視圖控制器的負荷,我打電話其中包含下面的代碼的方法:
HollerWebService *api = [[HollerWebService alloc]init];
//NSLog(@"About to get the hollers for userId: %@", [[[CurrentSession defaultStore]currentUser]userId]);
[api getLatestHollers:[[[CurrentSession defaultStore]currentUser]userId] completionBlock:^(BOOL succeeded) {
//If the user has 0 hollers, display one of the illustrations
[self.tableView reloadData];
[self stopLoading];
if(!succeeded){
UIAlertView *av = [[UIAlertView alloc] initWithTitle:@"Error" message:@"Could not connect to Holler" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[av show];
[av release];
}
else
{
for(Holler *hN in [[HollerStore defaultStore] allHollers])
{
//Retain count of all the hollers is
NSLog(@"Retain count of the holler is %i", [hN retainCount]);
}
}
}];
[api release];
正如你所看到的,我有一個評論面積打印出的保留計數的NSLog那是我的調試過程的一部分。此時,它告訴我每個對象的保留計數是2,這意味着在下一組代碼中生成的原始Holler尚未被自動釋放。下一組代碼在我的實際Web服務中。我已經包含了解決這個方法的重要組成部分,其導致增加保留計數評論:
- (void)getLatestHollers: (NSString *)userId completionBlock:(void (^)(BOOL succeeded))handler
{
[self getRequest:[[NSString alloc]initWithFormat:@"hollers/feed?user_id=%@",userId] completionBlock:^(NSData *receivedData, NSURLResponse *receivedResponse, NSError *error) {
if(error == nil)
{
SBJsonParser *json = [SBJsonParser new];
NSArray *response = [json objectWithData:receivedData];
[json release];
//NSLog(@"Got the latest Hollers. %@", response);
HollerStore *hStore = [HollerStore defaultStore];
for(NSDictionary *holler in response)
{
//At this point Holler *h is being sent an autoreleased holler
//from the parseHoller: method. At this point it's retain count is 1
Holler *h = [self parseHoller:holler];
[hStore addHoller:h];
//Now that I've added it to my singleton the retain count is 2, although I'm
//assuming the autorelease pool will eventually come through and reduce this
//to 1 but it never happens
}
handler(YES);
}
else
{
NSLog(@"The API failed :(, %@", [error localizedDescription]);
//Let the requestor know that this request failed
handler(NO);
}
}];
}
在這一點上保持數保持在2,而不是1,所以當我去從我的單身刪除對象它會導致內存泄漏。唯一可以總結的是,我遇到了一些與塊有關的內存問題。如果有人能提供一些見解,將非常感謝!
嗯,我已經使用了泄漏工具,它提供了一點洞察力。至於retaincount,我昨天使用了這個功能來查找一個bug。 –
'retainCount'無用;總有一種更好的方式。 – bbum
bbum非常感謝你的評論:) –