gpt4 book ai didi

iphone - 为什么这段 Objective C 代码会泄漏内存?

转载 作者:行者123 更新时间:2023-12-03 17:17:02 27 4
gpt4 key购买 nike

已更新

我在 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]];

当执行以下行时,Instruments 说我泄漏了 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;
}

关于iphone - 为什么这段 Objective C 代码会泄漏内存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3825409/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com