条件值(如while循环)作为方法参数

时间:2012-06-03 17:06:57

标签: objective-c loops boolean truthiness

所以,我试图有一种有效地做到这一点的方法:

- (void)doWhile: (/*some magical type*/)condition
{
    while (condition)
    {
        // do some magical things
    }
}

虽然您的第一个建议可能是BOOL,但请考虑以下例外情况:

[someObject doWhile: someOtherObject];
// yes, I know that I could just do (someOtherObject != nil), but
// I should be able to just use (someOtherObject), right?
// seeing as how ifs/fors/whiles can use just the object.

[someObject doWhile: [someOtherObject isValid]];
// since -isValid returns a BOOL, this will work, but it will only
// pass the value of -isValid at the time of calling to the while loop.
// if the value of -isValid changes, -doWhile: will have no idea of the change,
// whereas while() would.

使用原语_Bool可以解决前一个问题,但后一个问题仍然存在。有没有办法像while()一样评估与类型无关的参数的真实性?

1 个答案:

答案 0 :(得分:0)

如评论中所述,即使较简单的方法可能适用于不需要完全动态评估的测试用例,传递块也是获得所需结果的通用方法。