簡體   English   中英

為什么儀器在此代碼中報告內存泄漏?

[英]Why is Instruments reporting memory leaks in this code?

快速提問,儀器在這里報告泄漏...

MyViewController *myVC = [[MyViewController alloc] initWithNibName:@"myView" bundle:nil];     
[self.navigationController pushViewController:myVC animated:YES];  //<<<<---- !00% leak according to Instruments
[myVC release];

我了解myVC由導航控制器保留,因此我認為當視圖從導航堆棧彈出時,導航控制器會釋放它們嗎?

另外,在我的一個循環中還有另一個棘手的問題,靜態分析器在這里報告潛在的泄漏...

//Walk through the scheduled alarms and create notifications
NSMutableArray *fireDates = [[NSMutableArray alloc] init];
for(NSDate *fireDate in fireDates)          //<<<<---- Static analyzer is reporting potential leak here
{
     UILocalNotification *localNotif = [[UILocalNotification alloc] init];
    if (localNotif == nil)
    {
        [fireDates release];
        return;
    }

    localNotif.fireDate = fireDate;  
    localNotif.timeZone = [NSTimeZone defaultTimeZone];

    localNotif.alertBody = [NSString stringWithFormat:@"%@", alarm.Label];
    localNotif.alertAction = NSLocalizedString(@"Launch", nil);

    localNotif.soundName = UILocalNotificationDefaultSoundName;

    localNotif.userInfo = infoDict;
    localNotif.repeatInterval = NSWeekCalendarUnit;

    [[UIApplication sharedApplication] scheduleLocalNotification:localNotif];
    [localNotif release];

}
[fireDates release];

我需要以某種方式釋放fireDate嗎?

在此先感謝您的幫助!

這些片段都很好,就像片段一樣。 如果沒有看到完整的代碼,就無法說出您是否在其他地方沒有做傻事。 您是否曾經發布過您的navigationController(可能在應用程序委托-dealloc )? 那是不重要的泄漏,但可能是觸發第一個警告的原因。


編輯 :關於第二個片段,代碼看起來不錯(盡管快捷方式返回的情況會打擾一些編碼人員,他們寧願看到break語句)。 在條件返回中缺少[localNotif release] (盡管顯然沒有必要)可能會[localNotif release]靜態分析器。

在第一個代碼段中,泄漏了什么? 儀器會告訴您分配該行的位置,而該行通常不是泄漏的“負責人”行(當然,行號通常會關閉,因為它會給您返回地址,而不是調用地址)。 我假設它是MyViewController泄漏了,而該工具實際上是在抱怨alloc(在回溯中,我認為是cmd-E)。

如果單擊內存地址旁邊的箭頭(您可能必須單擊一下並懸停在泄漏地址上;我不記得了),您將看到所有的alloc / retain / release / autorelease / malloc / free / CFRetain / CFRelease調用該地址。 忽略alloc之前的那些(那些是針對先前居住在同一地址的對象的)。 比賽保留和(自動)釋放。 您可以將自動釋放與相應的(延遲的)釋放進行匹配,因為延遲釋放將在釋放NSAutoreleasePool時發生(這在堆棧跟蹤中很明顯)。 查找沒有匹配(自動)發布的保留。 那是泄漏。

在第二種情況下,如果您告訴我們Clang SA告訴您的內容,它會有所幫助(單擊左側的小三角形,它會展開以向您顯示發生泄漏的控制流)。

但我認為循環根本不會運行,因為fireDates為空。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM