簡體   English   中英

為什么此Objective C代碼會泄漏內存?

[英]Why does this Objective C code leak memory?

更新

我在目標C中有此方法:

-(NSDate*)roundTo15:(NSDate*)dateToRound {
    int intervalInMinute = 15;
    // Create a NSDate object and a NSDateComponets object for us to use
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:dateToRound];

    // Extract the number of minutes and find the remainder when divided the time interval
    NSInteger remainder = [dateComponents minute] % intervalInMinute; 
    // gives us the remainder when divided by interval (for example, 25 would be 0, but 23 would give a remainder of 3

    // Round to the nearest 5 minutes (ignoring seconds)
    if (remainder >= intervalInMinute/2) {
        dateToRound = [dateToRound dateByAddingTimeInterval:((intervalInMinute - remainder) * 60)]; // Add the difference
    } else if (remainder > 0 && remainder < intervalInMinute/2) {
        dateToRound = [dateToRound dateByAddingTimeInterval:(remainder * -60)]; // Subtract the difference
    }

    return dateToRound;
}

這就是我所說的方法:

item.timestamp = 
    [self roundTo15:[[NSDate date] dateByAddingTimeInterval:60 * 60]];

儀器說執行以下行時,我正在泄漏NSDate對象:

dateToRound = [dateToRound dateByAddingTimeInterval:(remainder * -60)];

因此,這是我的項目對象,需要使用新的更正的NSDate更新。 我嘗試制作一個roundedDate並按如下方式返回: return [roundedDate autorelease]; ,但隨后出現訪問錯誤。

問題是dateToRound被傳遞為對一個對象的引用,而您將其設置為對另一對象的引用。 現在,原始對象已被丟棄,並且已經泄漏。

您應該創建一個新的NSDate *並返回它,而不是重新分配dateToRound

樣例代碼:

-(NSDate*)roundTo15:(NSDate*)dateToRound {
    int intervalInMinute = 15;
    // Create a NSDate object and a NSDateComponets object for us to use
    NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:dateToRound];

    // Extract the number of minutes and find the remainder when divided the time interval
    NSInteger remainder = [dateComponents minute] % intervalInMinute; // gives us the remainder when divided by interval (for example, 25 would be 0, but 23 would give a remainder of 3

    // Round to the nearest 5 minutes (ignoring seconds)
    NSDate *roundedDate = nil;
    if (remainder >= intervalInMinute/2) {
        roundedDate = [dateToRound dateByAddingTimeInterval:((intervalInMinute - remainder) * 60)]; // Add the difference
    } else if (remainder > 0 && remainder < intervalInMinute/2) {
        roundedDate = [dateToRound dateByAddingTimeInterval:(remainder * -60)]; // Subtract the difference
    } else {
        roundedDate = [[dateToRound copy] autorelease];
    }

    return roundedDate;
}

某些類方法可能代表您返回一個對象。 檢查文檔,但是我猜想dateByAddingTimeInterval可以。 也就是說,返回的對象未設置為autorelease 在這種情況下,您需要自己release它。

我發現Instruments報告了一些不那么直觀的事情。 不要誤會我的意思,它是一個很棒的工具,而且您正在使用。 但是,甚至來自Apple的一些示例代碼也報告了泄漏。

暫無
暫無

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

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