繁体   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