Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory Leak while using NSDateFormatter

I have seen many questions/answers on memory leaks in NSDateFormatter, but none seems to help me determine what is causing memory to leak in my app. Here is my code:

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

When I run "Profile" -> "Leaks", I get a memory leak every time the function is called on line

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

Can someone explain what might be going on? thanks, mike

like image 746
mike.tihonchik Avatar asked Apr 20 '12 21:04

mike.tihonchik


2 Answers

FYI you can change this:

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

to this:

 NSString *stringFromDate = [format stringFromDate:fromDate];

stringWithString should return an autoreleased NSString though so I don't believe that is the source of your leak. It looks like there is no leak in your code to me.

like image 52
Michael Frederick Avatar answered Nov 02 '22 21:11

Michael Frederick


you just use bellow method for get string from date its work properly......

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

after when you want to get date string just use like bellow....

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

and above -(NSString *)StringFromDate:(NSDate *)DateLocal method is must be define in your viewcontroller.m file.... Its work fine....

like image 33
Paras Joshi Avatar answered Nov 02 '22 21:11

Paras Joshi