为什么这个Objective C代码会泄漏内存?

时间:2010-09-29 20:04:39

标签: iphone objective-c cocoa

已更新

我在Objective 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进行更新。我尝试创建一个舍入的数字并返回它:return [roundedDate autorelease];,但后来我遇到了错误的访问错误。

2 个答案:

答案 0 :(得分:3)

问题是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;
}

答案 1 :(得分:-2)

某些类方法可能代表您返回 new 对象。检查文档,但我的猜测是dateByAddingTimeInterval。也就是说返回的对象未设置为autorelease。在这种情况下,您需要自己release

我发现仪器会报告一些不那么直观的东西。不要误会我的意思,这是一个很棒的工具,你使用的很棒。但即便是苹果公司的一些示例代码也报告泄密。

相关问题