Obj-c - 一个如果Statement覆盖另一个?

时间:2018-02-18 01:01:18

标签: objective-c

我有两个if语句 - 请参阅下面的代码:

的.m

if ([swaptime isKindOfClass:[NSString class]] && [friends count] > 0) {

} 

if ([friends count] > 0) {

}

按原样,我的第二个if语句有时会覆盖第一个,即使swaptime的值已填充 AND 的朋友数大于0.即使两个语句都要求朋友数大于0,如果swaptime为NULL,那么第二个if语句是否只能启动?还是有另一种方式我应该写这个?

2 个答案:

答案 0 :(得分:2)

你的意思是:

if ([swaptime isKindOfClass:[NSString class]] && [friends count] > 0) 
{

} 
else if ([friends count] > 0) 
{

}

每当[朋友计数]>执行第二次if时的执行方式0,忽略[swaptime isKindOfClass:[NSString class]]是否为真。

重复代码通常是件坏事。我这样说:

if ([friends count] > 0)
{
    if ([swaptime isKindOfClass:[NSString class]]
    {

    }
    else
    {

    }
}

会提供更易理解的代码...

答案 1 :(得分:0)

它应该是else if ([friends count] > 0) ..或者将它们写成连续的条件语句或嵌套语句。

示例1:

if ([swaptime isKindOfClass:[NSString class]] && [friends count] > 0) {
    //Execute code where because swapTime is `NSString` and `friends.count > 0`..
} 
else if ([friends count] > 0) {
    //Execute code here if `swapTime` is anything other than `NSString` (including nil) and `friends count > 0`
}

示例2:

if ([swaptime isKindOfClass:[NSString class]] && [friends count] > 0) {
    //Execute code where because swapTime is `NSString` and `friends.count > 0`..
} 
else if (swaptime != nil && [friends count] > 0) {
    //Execute code here if `swapTime` is non-null and not `NSString` and `friends count > 0`
}
else if ([friends count] > 0) {
    //Execute code here if `swapTime` is null/nil and `friends count > 0`
}

示例3:

if ([friends count] > 0) {
    if ([swaptime isKindOfClass:[NSString class]]) {
        //Execute code here if swapTime is NSString..
    }
    else if (swaptime) {
        //Execute code here if swapTime is non-null and NOT an NSString..
    }
    else {
        //Execute code here if swapTime is null..
    }
}