Why doesn't NSDateFormatter return a NSString?
Why does this message not retu开发者_如何学运维rn a string:
NSDate *today = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *formattedDate = (@"Date for today %@:", [dateFormatter stringFromDate:today]);
That expression does return an NSString, but without formatting. To format an NSString properly, you use the +stringWithFormat:
method:
NSString* formattedDate = [NSString stringWithFormat:@"Date for today %@:",
[dateFormatter stringFromDate:today]];
The expression a, b
is a "comma expression". It will evaluate a
and b
in sequence, and return the value of b
. In you case, it will return the string of date only.
Most of the case, you do not want to use a comma expression.
Also, the dateFormatter
needs to be configured before using. For instance,
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setTimeStyle:NSDateFormatterNoStyle];
[dateFormatter setDateStyle:NSDateFormatterMediumStyle];
...
... [dateFormatter stringFromDate:today] ...
...
[dateFormatter release];
精彩评论