Search code examples
objective-cassert

Assert with string argument not working as expected


EDIT: The issue was with the assert as people pointed out below. Thanks for the help!

I have a enum set that i'm trying equate, but for some reason its not working. Its declared like so:

typedef NS_ENUM(NSUInteger, ExUnitTypes) {
    kuNilWorkUnit,
    kuDistanceInMeters,
    //end
    kuUndefined
};

And i'm using it here:

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

Xcode isnt triggering my assert. EDIT: the assert is just for testing. i've used NSLog as well. The conditional isn't evaluating to true even though the value is clearly kuNilWorkUnit.

xcode enum asser image

Does anyone have any suggestions or ideas of what i'm doing wrong?


Solution

  • You want to do this:

    +(NSString*) ExUnitDescription: (ExUnitTypes) exUnit
    {
        assert(exUnit != kuNilWorkUnit);
    
        ///.... more stuff
    }
    

    This is because, assert only stops execution if the expression you pass to it is false. Since a string literal is always non-zero, it will never stop execution.

    Now, since you are using Objective C and it also looks like you want to have a message associated with your assert, NSAssert would be preferable.

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