2010-07-31 24 views
0

第一招:爲什麼這些方法泄漏NSDate對象?

+ (NSDate*)convertToUTC:(NSDate*)sourceDate 
{ 
    NSTimeZone* currentTimeZone = [NSTimeZone localTimeZone]; 
    NSTimeZone* utcTimeZone = [NSTimeZone timeZoneWithAbbreviation:@"UTC"]; 

    NSInteger currentGMTOffset = [currentTimeZone secondsFromGMTForDate:sourceDate]; 
    NSInteger gmtOffset = [utcTimeZone secondsFromGMTForDate:sourceDate]; 
    NSTimeInterval gmtInterval = gmtOffset - currentGMTOffset; 

    return [NSDate dateWithTimeInterval:gmtInterval sinceDate:sourceDate]; 
} 

是的,我知道這下一個是陌生的,但我的服務器給我狠狠打了一下日期格式

+(NSDate *)getDateFromString:(NSString *)dtStr 
{ 
NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init]; 
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; 
[inputFormatter setLocale:locale]; 
[locale release]; 
[inputFormatter setDateFormat:@"MMMM, dd yyyy HH:mm:ss"]; 
NSDate *formatterDate = [[inputFormatter dateFromString:dtStr] copy]; 
[inputFormatter release]; 
return formatterDate; 
} 

回答

3

第一個沒有,但第二個呢,因爲你創建了一個副本並且沒有自動釋放它。如果你稍後不發佈,它會被泄露。

我不明白你爲什麼要在第二種方法中複製日期。只要將其切除即可修復泄漏。

您確實應該閱讀(或重新閱讀)the Memory Management Programming Guide for Cocoa,因爲您似乎需要改進對內存管理規則的理解。