繁体   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