簡體   English   中英

iOS NSString stringWithString使用ARC時導致內存泄漏

[英]iOS NSString stringWithString cause memory leak when using ARC

我要在發布通知時傳遞一些數據,該數據是包含本地通知信息的字典。

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString *uuid = [NSString stringWithString:notification.userInfo[@"UUID"]];
NSDictionary *infoDic = @{
                          @"UUID" :uuid
                          };
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"PopReminder"
     object:nil
     userInfo:infoDic];
}

}

通知就像notification.userInfo = @{ @"UUID" : list.itemKey }

list.itemKey是用於標識特定列表的字符串。

NSUUID *uuid = [[NSUUID alloc] init]; NSString *key = [uuid UUIDString]; list.itemKey = key;

但是,當使用Leak進行測試時,它顯示了一個NSString對象,導致內存泄漏。 類方法如何會導致內存泄漏,並且它正在使用ARC。 有人可以幫助找到解決方案嗎? 謝謝。

在此處輸入圖片說明

以另一種方式解決,但仍不清楚泄漏原因:

- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
NSString *uuid;
NSArray *lists = [YYList MR_findAll];
for (YYList *list in lists) {
    if ([list.itemKey isEqualToString:notification.userInfo[@"UUID"]]) {
        uuid = [list.itemKey copy];
    }
}
if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"PopReminder"
     object:nil
     userInfo:@{
                @"UUID" :uuid
                }];
}

}

這樣,它可以很好地工作。 但是仍然想知道為什么不能直接使用[notification.userInfo [@“ UUID”]副本]傳遞數據。 在“泄漏”中,它表明這是一個泄漏周期,也許這是表明我錯過了某些事情的線索。 如果是這樣,以哪種方式導致UILocalNotification'notification'和NSNotification'PopReminder'相互保留?

無需對傳入的userInfo進行任何重新處理。您可以直接將其直接傳遞。

同時,Instruments告訴您在此創建的對象最終會泄漏。 這意味着捕獲PopReminder正在導致對象泄漏。 在那調查。 盡管您的任意[NSString stringWithString:]需求為零,但這不是無效的。

下列:

- (void)application:(UIApplication *)application didReceiveLocalNotification:(UILocalNotification *)notification {
    if ([UIApplication sharedApplication].applicationState == UIApplicationStateActive) {
        [[NSNotificationCenter defaultCenter]
         postNotificationName:@"PopReminder"
         object:nil
         userInfo:notification.userInfo];
    }
}

...是您提供的方法的完美,完整的版本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM