使用NSDateFormatter时内存泄漏

时间:2012-04-20 21:47:14

标签: iphone objective-c nsdateformatter

我在NSDateFormatter中看到了很多关于内存泄漏的问题/答案,但似乎没有一个能帮助我确定导致内存在我的应用程序中泄漏的原因。这是我的代码:

- (id)init
{
    if ((self = [super init])) 
    {
        items = [[NSMutableArray alloc] init];
        events = [[NSMutableArray alloc] init];
        buffer = [[NSMutableData alloc] init];
        format = [[NSDateFormatter alloc] init];
        lastFromDate = @"";
    }
    return self;
}

- (void)presentingDatesFrom:(NSDate *)fromDate to:(NSDate *)toDate delegate:(id<KalDataSourceCallbacks>)delegate
{ 
    [format setTimeZone:[NSTimeZone systemTimeZone]];
    [format setDateFormat:@"MM/dd/yyyy"];
    NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];
    NSString *stringToDate = [NSString stringWithString:[format stringFromDate:toDate]];

    NSLog(@"From date: %@, To date: %@", stringFromDate, stringToDate); 

    [self didDatesChange:stringFromDate];

    if (dataReady) {
        [callback loadedDataSource:self];
        return;
    }
    callback = delegate;
    [self retrieveEventData:stringFromDate to:stringToDate];
}

- (void)dealloc
{
    [items release];
    [events release];
    [buffer release];
    [lastFromDate release];
    [format release];
    [super dealloc];
}

当我运行“个人资料”时 - &gt; “泄漏”,每次在线调用函数时都会出现内存泄漏

NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];

有人可以解释可能发生的事情吗? 谢谢,迈克

2 个答案:

答案 0 :(得分:2)

仅供参考,你可以改变这个:

 NSString *stringFromDate = [NSString stringWithString:[format stringFromDate:fromDate]];

到此:

 NSString *stringFromDate = [format stringFromDate:fromDate];

stringWithString应该返回一个自动释放的NSString,所以我不相信这是你泄漏的来源。看起来您的代码中没有泄漏给我。

答案 1 :(得分:2)

你只需使用bellow方法从日期获取字符串就可以正常工作......

-(NSString *)StringFromDate:(NSDate *)DateLocal{
    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
    [dateFormat setDateFormat:@"MM/dd/yyyy"];
    NSString *dateString = [dateFormat stringFromDate:DateLocal];  
    NSLog(@"Date is HERE  =====>> %@",dateString);
    return dateString;
}

之后你想获得日期字符串就像使用贝娄一样......

NSString *stringFromDate = [self stringFromDate:fromDate]];
[stringfromdate retain];
NSString *stringToDate = [self stringFromDate:toDate]];
[stringTodate retain];

及以上 - (NSString *)StringFromDate:(NSDate *)必须在viewcontroller.m文件中定义DateLocal方法.... 它的工作正常......