繁体   English   中英

Xcode:存储到“通知”中的对象的潜在泄漏

[英]Xcode: Potential leak of an object stored into 'notification'

我遇到了一个使我的应用程序崩溃的问题,并且我已经尽一切努力对其进行了更改,但是没有运气。 因此,我希望新的眼睛能对我有所帮助。

这是我的代码的视图:

。H

@property (nonatomic, retain) UILocalNotification *notification;

.m

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
    notification.alertBody = @"Skal du ikke træne i dag? Det tager kun 7 minutter!";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

}

分析时会出现以下错误:

  • 存储在“通知”中的对象的潜在泄漏

我真的希望你们中的一个能帮助我。 谢谢!

与您的其他问题类似,更改:

UILocalNotification *notification = [[UILocalNotification alloc] init];

至:

self.notification = [[UILocalNotification alloc] init];

并使用self.notification代替其他地方的notification 当您使用最新版本的Xcode时,默认情况下将启用ARC。 如果是这样,则以上关于使用release的答案是错误的。

注意:编辑此答案以使用属性点表示法,而不是直接访问ivar。 有关更多背景知识, 请参见此 SO答案: self.iVar对于ARC的强大属性是否必要?

您需要-release-autorelease新通知。 简洁的方法是:

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    UILocalNotification * notification =
      [[[UILocalNotification alloc] init] autorelease];
                                          ^^^^^^^^^^^

    notification.fireDate = [[NSDate date] dateByAddingTimeInterval:60*60*24];
    notification.alertBody = @"Skal du ikke træne i dag? Det tager kun 7 minutter!";
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];

}

系统(很大程度上)依赖于命名约定。 初始化程序(例如-init ),复印机(副本,mutableCopy)和+new是返回必须释放(或自动释放)实例的方法的示例。

还要注意, UILocalNotification * notification = ...声明了一个位于方法主体局部的新变量,该变量UILocalNotification * notification = ...了您的notification属性。

您正在分配本地UILocalNotification但不释放它。 至少不在您发布的代码中。 分析器抓住了您,因为它看不到资源被释放。 如果要释放到其他地方,则分析仪将无法合法捕获它。

要解决此问题,您应该将局部变量分配给您的媒体资源,以确保媒体资源的所有者(看起来像应用程序委托)始终保持对该通知的引用。

self.notification = notification;

在退出该方法之前,请先释放它,以确保平衡您的保留数。

[notification release];

最后,使用通知完成后,您可以取消属性。 从应用程序委托中释放它。 使用完毕后,请务必执行此操作。

self.notification = nil

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM