2010-07-01 74 views
0

進出口新的OBJ-c和需要一些幫助,這代碼Objective-C的錯誤捕獲

NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease]; 
[dateFormatter setDateFormat:@"E, d LLL yyyy HH:mm:ss Z"]; 
NSDate *date = [dateFormatter dateFromString:currentDate]; 

變量日期不能是零。我怎樣才能讓日期=當前時間無法格式化字符串? 我可以使用try/catch嗎?怎麼樣?

回答

4

爲什麼只是沒有檢查日期從格式返回,如果是零指定當前的日期,以它?

NSDate *date = [dateFormatter dateFromString:currentDate]; 
if (!date) 
    date = [NSDate date]; 

或者使用三元操作符(及其擴展GCC)1班輪:

NSDate *date = [dateFormatter dateFromString:currentDate]?:[NSDate date]; 
+0

我不知道有關GCC的擴展。非常非常酷。其他語言有類似的東西,比如C#及其''''操作符。 – Paul 2010-07-01 14:51:39

+0

你會如何在c#中編寫這個? – Yaso 2010-07-01 18:31:38

0

能試試這個:

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

這樣做會很糟糕,因爲'@ try'塊中返回的對象是自動釋放並且'@ catch'塊返回的對象不是。你最好在'@ catch'塊中使用'[NSDate date]''。 – Paul 2010-07-01 14:50:40

+0

謝謝你。編輯。 – 2010-07-01 14:55:50

+0

@paul [NSDate date]在內存管理方面有什麼不同?我是新來的。 – Yaso 2010-07-01 18:34:49

0

應該不起作用:

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

爲什麼downvote? – 2010-07-01 08:48:00

+0

[dateFormatter dateFromString:currentDate] ||的結果[NSDate date]是BOOL不是嗎? – Vladimir 2010-07-01 08:49:09

+0

不,它不是afaik,它可以是'[dateFormatter dateFromString:currentDate]',或者如果結果布爾值爲false(在本例中爲'nil'),它將是'[NSDate date]'。我只是用JavaScript測試它,它在那裏工作,但我不能說100%的確定它在(Objective-)C中的作用是一樣的... – 2010-07-01 08:52:12

0

,你不應該這樣做,因爲NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];的自動釋放,使對象的生命週期不確定。在完成之後,省略autorelease並釋放該對象。 (如果您不確定:當您將對象賦予啓用了retain的屬性時,您會看到類似的分配(使用autorelease))