2013-05-01 139 views
0

我的問題可能很簡單。 我有一個自定義寫入指定的初始值設定項,它獲取BOOL參數。具有BOOL參數和異常的自定義指定初始值設定項?

其中,我想檢查是否有BOOL通過或其他。 如果還有其他問題,我想提出例外。

我也想覆蓋默認的init並將其指向我的指定初始化程序而不是調用super,並在其中傳遞一個nil,以便用戶在不使用指定初始化程序時獲得適當的異常。

-(id)init 
{ 
    return [self initWithFlag:nil]; 
} 


-(id)initWithFlag:(BOOL)flag 
{ 
    //get the super self bla bla 

    if (flag IS-NOT-A-BOOL) 
    { 
     //raising exception here 
    } 
    //store the flag 

    return self; 
} 

什麼應該代替IS-NOT-A-BOOL?

回答

0

目標c中的BOOL可能會導致YES或NO,並且所有內容都將被轉換爲其中一個值。如何使用包含bool值的NSNumber?像:

-(id)initWithFlag:(NSNumber *)flag 
{ 
    //get the super self bla bla 

    if (!flag) // Check whether not nil 
    { 
     //raising exception here 
     [NSException raise:@"You must pass a flag" format:@"flag is invalid"]; 
    } 
    //store the flag 
    BOOL flagValue = [flag boolValue]; 

    return self; 
} 

在這種情況下,你可以這樣調用

[self initWithFlag:@YES]; // or @NO, anyway, it won't throw an exception 

的方法或本

[self initWithFlag:nil]; // it will throw an exception 
+1

明確拳擊是不必要的布爾文字。 '@ YES'和'@ NO'工作得很好。 – CodaFi 2013-05-01 14:31:57

+0

的確,我只是更新了答案。謝謝 – 2013-05-01 14:35:10

相關問題