【问题标题】:Memory Leak with Date Stuff (__NSCFCalendar, icu::GregorianCalendar)带有日期内容的内存泄漏 (__NSCFCalendar, icu::GregorianCalendar)
【发布时间】:2011-04-01 19:02:49
【问题描述】:

我有一个返回给定日期的第一个工作日的小方法:

- (NSDate*) getFirstDayOfTheWeekFor:(NSDate*)date {

NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDate *firstDayDate; //This is 100.0% leaking acc. to the Performance Tool Leaks

unsigned yearAndWeek = NSYearCalendarUnit | NSWeekCalendarUnit;

// retrieve the components from the current date
NSDateComponents *compsCurrentDate = [[gregorianCalender components:yearAndWeek fromDate:date] autorelease];

[compsCurrentDate setWeekday:2]; // Monday
[compsCurrentDate setHour:0];
[compsCurrentDate setMinute:0];
[compsCurrentDate setSecond:0];

// make a date from the modfied components
firstDayDate = [[gregorianCalender dateFromComponents:compsCurrentDate] autorelease];   

return firstDayDate;
}

如您所见,我已经在尝试自动释放此处使用的每个变量(这不是我开始追踪泄漏之前的样子)。本来想在return前显式释放所有变量,除了“firstDayDate”变量,因为return所以必须自动释放。

这些是性能工具发现的泄漏对象:

  • icu::GregorianCalendar (1.00 KB)
  • icu::SimpleTimeZone(112 字节)
  • __NSDate(16 字节)
  • icu::NSNumberingSystem(128 字节)
  • __NSCFCalendar(48 字节)

这个错误一定是完全愚蠢的,但我找不到。你能帮助我吗?谢谢!!

【问题讨论】:

    标签: iphone ios memory-leaks gregorian-calendar


    【解决方案1】:

    应该是这样的:

    - (NSDate*) getFirstDayOfTheWeekFor:(NSDate*)date
    {
        NSCalendar *gregorianCalender = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
        NSDate *firstDayDate; //This is 100.0% leaking acc. to the Performance Tool Leaks
    
        unsigned yearAndWeek = NSYearCalendarUnit | NSWeekCalendarUnit;
    
        // retrieve the components from the current date
        NSDateComponents *compsCurrentDate = [gregorianCalender components:yearAndWeek fromDate:date];
    
        [compsCurrentDate setWeekday:2]; // Monday
        [compsCurrentDate setHour:0];
        [compsCurrentDate setMinute:0];
        [compsCurrentDate setSecond:0];
    
        // make a date from the modfied components
        firstDayDate = [gregorianCalender dateFromComponents:compsCurrentDate];
    
        return firstDayDate;
    }
    

    如果 firstDayDate 泄漏,则不在此方法中。检查下游。此外,对我来说,icu 部分看起来有点可疑。这可能是 icu 库周围的 iOS 包装器中的错误/泄漏。

    如果你是alloc, init,请记住你只有releaseautorelease,或者copy

    【讨论】:

    • 是的,对我来说 icu 部分也很可疑 .. 感谢您的快速回答,希望其他人现在可以了解这些 icu 对象的全部内容。
    • 还可以查看调用此方法的任何代码。它很可能会保留该值而不释放,我的猜测是将其设置为某个未正确释放的属性。正如 amattn 所说,您的泄漏在该代码中不存在。
    猜你喜欢
    • 2012-12-23
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-14
    • 2012-04-06
    相关资源
    最近更新 更多