2013-05-01 62 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

相关问题