why
why

Reputation: 24851

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.

Upvotes: 3

Views: 1640

Answers (2)

Ganapathy
Ganapathy

Reputation: 4614

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

Upvotes: 2

Apurv
Apurv

Reputation: 17186

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

Upvotes: 1

Related Questions