Im new to obj-c and need some help with this code
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormatter dateFromString:currentDate];
the variable date cannot be nil. how can I make it so that date = current time when it's unable to format the string? can i use try/catch? how?
Why just not check the date returned from formatter and if it is nil assign current date to it?
NSDate *date = [dateFormatter dateFromString:currentDate];
if (!date)
date = [NSDate date];
Or 1-liner using ternary operator (and its gcc extension):
NSDate *date = [dateFormatter dateFromString:currentDate]?:[NSDate date];
Could try this :
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"];
NSDate *date = nil;
@try
{
date = [dateFormatter dateFromString:currentDate];
}
@catch (NSException *exception)
{
date = [NSDate date];
}
这应该不工作:
NSDate *date = [dateFormatter dateFromString:currentDate] || [NSDate date];
you should not do that NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
because the autorelease makes the object lifetime uncertain. Omit the autorelease
and release the object instead when you are done with it. (In case you are unsure: you see allocation like that (with autorelease) quite frequently when you give the object to a property which has retain
enabled)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.