Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory leaks with NSDateFormatter

When I profile my iOS application, I found too much Memory leaks: enter image description here

There is my code with NSDateFormatter and the code is in one loop:

 for (NSDictionary * dataDict in deserializedData) {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    NSTimeZone *timeZone = [NSTimeZone localTimeZone];
    [dateFormatter setTimeZone:timeZone];
    [dateFormatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
    NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
    [dateFormatter release];
}

Who can tell me what's wrong with my code.

like image 573
why Avatar asked Nov 22 '25 02:11

why


2 Answers

Just try with auto release like this,

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
[dateFormatter setTimeZone:timeZone];
[dateFormatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];

for (NSDictionary * dataDict in deserializedData) {
    NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
}
like image 86
Ganapathy Avatar answered Nov 24 '25 17:11

Ganapathy


There is nothing wrong in this code. But I think it is not called on main thread.

Just create an autorelease pool on the beginning of the function in which you have written this code. At the end of the function release the pool.

-(void) yourFun
{
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //other stuff...

    for (NSDictionary * dataDict in deserializedData) {
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [dateFormatter setTimeZone:timeZone];
        [dateFormatter setDateFormat : @"yyyy-MM-dd HH:mm:ss"];
        NSString *currentDateString = [dateFormatter stringFromDate:[NSDate date]];
        [dateFormatter release];
    }

    [pool release];
}
like image 29
Apurv Avatar answered Nov 24 '25 19:11

Apurv



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!