Yaso
Yaso

Reputation: 643

objective-c error catching

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?

Upvotes: 0

Views: 400

Answers (4)

Russo
Russo

Reputation: 405

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)

Upvotes: 0

OMG_peanuts
OMG_peanuts

Reputation: 1817

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

Upvotes: 0

Douwe Maan
Douwe Maan

Reputation: 6878

This should doesn't work:

NSDate *date = [dateFormatter dateFromString:currentDate] || [NSDate date];

Upvotes: 0

Vladimir
Vladimir

Reputation: 170839

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

Upvotes: 4

Related Questions