iPhone, if I'm converting a date string from one format to another, to store it, do I have to convert it to a date, how?
I need to show a date in a certain format 开发者_JAVA技巧on screen, but I need to store the date as a string in another format. I think this means I have to convert it to a date and back to a string.
How do i do this ?
I have already figured out how to convert my string to a date, however build analyser gives me a warning.
I want to convert the string from dd MM yyyy to yyyy-MM-dd
He my code so far...
NSString *startDateString = btnStartDate.titleLabel.text;
NSDateFormatter *dateStartFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateStartFormatter setDateFormat:@"dd MM yyyy"];
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];
The analyzer warns you of a leak. First, you assign a new object to datStartDate
, and then you store a new value with datStartDate = [dateStartFormatter dateFromString:startDateString];
without releasing the previous object first.
So instead of:
NSDate *datStartDate = [[NSDate alloc] init];
datStartDate = [dateStartFormatter dateFromString:startDateString];
You should just write:
NSDate *datStartDate = [dateStartFormatter dateFromString:startDateString];
Well you're allocating space for datStartDate
for a new NSDate
, then replacing it with a completely new NSDate
from your date formater (now you have memory set aside for the first NSDate
that is never going to be used)
Use this:
NSDate* datStartDate = [dateStartFormater dateFromString:startDateString];
then use your dateStartFormater
or another NSDateFormatter
to turn your date into the required string like so:
[dateStartFormatter setDateFormat:@"yyyy MM dd"];
NSString* formatedDate = [dateStartFormater stringFromDate:datStartDate];
精彩评论