使用字符串参数断言无法按预期工作

Shr*_*der 0 assert objective-c

编辑:正如人们在下面指出的那样,问题与断言有关。谢谢您的帮助!

我有一个枚举集,我试图将其等同,但由于某种原因,它无法正常工作。其声明如下:

typedef NS_ENUM(NSUInteger, ExUnitTypes) {
    kuNilWorkUnit,
    kuDistanceInMeters,
    //end
    kuUndefined
};
Run Code Online (Sandbox Code Playgroud)

我在这里使用它:

  +(NSString*) ExUnitDescription: (ExUnitTypes) exUnit
{
    if (exUnit == kuNilWorkUnit)
    {
        assert("error with units");
    }
///.... more stuff
}
Run Code Online (Sandbox Code Playgroud)

Xcode不会触发我的断言。编辑:断言仅用于测试。我也用过NSLog。即使该值显然是kuNilWorkUnit,该条件的取值也不是正确的。

xcode枚举器映像

有人对我做错事情有任何建议或想法吗?

Lan*_*nce 5

您想这样做:

+(NSString*) ExUnitDescription: (ExUnitTypes) exUnit
{
    assert(exUnit != kuNilWorkUnit);

    ///.... more stuff
}
Run Code Online (Sandbox Code Playgroud)

这是因为assert仅在传递给它的表达式为false时才停止执行。由于字符串文字总是非零的,因此它将永远不会停止执行。

现在,由于您使用的是Objective C,而且看起来还想与自己的assert关联一条消息,所以NSAssert是更好的选择。

+(NSString*) ExUnitDescription: (ExUnitTypes) exUnit
{
    NSAssert(exUnit != kuNilWorkUnit, @"error with units");

    ///.... more stuff
}
Run Code Online (Sandbox Code Playgroud)