xcode中:存储到“通知”的物体的潜在的泄漏(Xcode: Potential leak of a

2019-10-18 08:18发布

我有一个让我的应用程序崩溃的问题,我想尽一切办法改变它,但没有运气。 因此,我希望一组新的眼睛可以帮助我一点点。

这里是我的代码视图:

。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];

}

分析它时,它给了我下面的错误:

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

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

Answer 1:

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

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

至:

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

并使用self.notification ,而不是notification别处。 当你使用最新版本的Xcode版本,ARC将默认启用。 如果是这样,使用上面关于答案release是不正确。

注:编辑这个答案使用属性点符号,而不是直接访问伊娃的。 看到这个SO回答上多一点背景: 是self.iVar必要与ARC强大的性能?



Answer 2:

您需要-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 = ...声明了一个新的局部变量的方法体,其阴影您notification财产。



Answer 3:

您分配一个本地UILocalNotification但不释放它。 在代码中至少不是你贴。 该分析仪抓到你,因为它没有看到被释放的资源。 如果你在其他地方释放,在一个合法的方式,分析仪将不能抓住它。

为了解决这个问题,你应该局部变量分配给你的财产,保证财产的所有者(看起来像应用程序委托)保持一个生活参考通知。

self.notification = notification;

和离开该方法,从而可以确保平衡你的保留计数之前释放。

[notification release];

最后,一旦你使用的通知可以零出你的财产做。 从应用程序的委托将其释放。 一定要做到这一点,一旦你用它做。

self.notification = nil


文章来源: Xcode: Potential leak of an object stored into 'notification'
标签: iphone ios xcode