converting NSDate
to NSString
creates a memory leak can anyone help.
Here is my code:-
NSDate *today = [[NSDate alloc]init];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
dateString = nil;
dateString =[[NSString alloc]initWithString:[df stringFromDate:today]];
[df setDateFormat:@"EEEE MMM dd yyyy"];
[dateButton setTitle:[df stringFromDate:today] forState:UIControlStateNormal];
[df release];
[today release];
Get Today's Date: NSDate* date = [NSDate date];
As you aren't releasing anything the code creates a memory leak.
NSDate *today = [NSDate date]; //Autorelease
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease]; //Autorelease
[df setDateFormat:@"yyyy-MM-dd"]; // 2017-09-28
dateString = [[df stringFromDate:today] retain];
[df setDateFormat:@"EEEE MMM dd yyyy"]; // Thursday Sep 28 2017
[dateButton setTitle:[df stringFromDate:today] forState:UIControlStateNormal];
For more details, you can refer to Apple's documentation.
Use
NSDate *today = [NSDate date];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
dateString = [df stringFromDate:today];
[df release]
Using your code...
NSDate *today = [[NSDate alloc]init];
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"yyyy-MM-dd"];
dateString = nil;
dateString = [[NSString alloc]initWithString:[df stringFromDate:today]];
...you need to release a lot of obj because nothing is in autorelease.
[today release]; -> alloc
[df release] -> alloc
[dateString release]; -> alloc
Or change to:
NSDate *today = [NSDate date];
NSDateFormatter *df = [NSDateFormatter initWithDateFormat:@"yyyy-MM-dd"];
dateString = [df stringFromDate:today];
with no one release/alloc!
The leak is in the DateFormatter that is not being released. This should fix the leak :
[df release];
Also, try using ...
[NSDate date]
instead of ...
NSDate* today = [[NSDate alloc] init];
that is a lot of alloc/initing that you are doing there as well... you don't need to alloc/init the NSString either.
You Shoud noy alloc or init NSDate object
Try this Code
NSDate *today = [NSDate date];
NSDateFormatter *dt = [[NSDateFormatter alloc]init];
[dt setDateFormat:@"yyyy-mm-dd"];
NSString *str =[NSString stringWithFormat:@"%@",[dt stringFromDate:today]];
NSLog(@"%@",str);
[dt release];
Happy Coding
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With