2013-07-03 100 views
1

我遇到了一个令我的应用程序崩溃的问题,并且我尝试了一切来改变它,但没有运气。所以我希望新的眼睛可以帮助我一点点。Xcode:存储到“通知”中的对象的潜在泄漏

这里是我的代码视图:

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

} 

它给我分析它,当出现以下错误:

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

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

+0

您没有在此方法中使用'notification'属性。这是你想在这里发布的代码吗?此外,潜在的泄漏并不需要与事故相关(可能不是)。 – Tricertops

+0

我对你的问题是:你为什么不使用ARC?如果你不知道它是什么,只需打开它;) – Tricertops

+0

作为一个方面说明:'60 * 60 * 24'不能保证现在给你+1天!时间**是**恶,请务必正确处理! – JustSid

回答

-1

您正在分配本地UILocalNotification但未释放它。至少不在您发布的代码中。分析器发现你,因为它没有看到资源被释放。如果你在其他地方发布,以合法的方式,分析仪将无法捕捉到它。

要解决此问题,您应该将本地变量分配给您的属性,以确保属性的所有者(看起来像应用程序委托)保持对通知的生动参考。

self.notification = notification; 

和离开方法之前释放,所以你要确保你的平衡保留计数。

[notification release]; 

最后,一旦你完成使用通知,你可以删除你的财产。从应用程序代理释放它。一旦你使用它,一定要这样做。

self.notification = nil 
0

到您的其他问题一样,变化:

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

到:

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

,并使用self.notification,而不是其他地方notification。当你使用最新版本的Xcode时,默认情况下会启用ARC。如果是这样,以上关于使用release的答案不正确。

注意:编辑此答案使用属性点符号而不是直接访问伊娃。 看到这个SO回答上一点点更多的背景:Is self.iVar necessary for strong properties with ARC?

+0

直接使用ivars是泄漏对象的好方法。 –

+0

同意直接使用ivars存在问题。我几乎只在我的代码中使用点符号(self.x)。只是遵循了我在另一个OP问题上给出的伊娃标记。有一个来自Apple的演示文稿我认为这是对属性与ivars的问题的总结,但我不知道在哪里可以找到它。更正了我使用propeties而不是ivars的答案。 – stevekohls

0

您需要-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属性。