2013-07-03 101 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屬性。