6

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

当我运行“配置文件”->“泄漏”时,每次在线调用函数时都会发生内存泄漏

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

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

4

2 回答 2

2

您只需使用以下方法从日期获取字符串即可正常工作......

-(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 *)DateLocal 方法必须在您的 viewcontroller.m 文件中定义......它工作正常......

于 2012-04-21T09:01:19.693 回答
2

仅供参考,您可以更改此设置:

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

对此:

 NSString *stringFromDate = [format stringFromDate:fromDate];

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

于 2012-04-20T21:57:26.013 回答