美文网首页
有关NSAssert相关知识点

有关NSAssert相关知识点

作者: 青波志 | 来源:发表于2016-03-03 09:40 被阅读13次

    苹果官方文档写的比较清楚:

    NSAssert

    Generates an assertion if a given condition is false.

    Declaration

    #define NSAssert(condition, desc, ...)
    

    Parameters

    condition:An expression that evaluates to YES or NO

    desc: An NSString object that contains a printf-style string containing an error message describing the failure condition and placeholders for the arguments

    ...:The arguments displayed in the desc string

    Discussion

    The NSAssert macro evaluates the condition and serves as a front end to the assertion handler.

    Each thread has its own assertion handler, which is an object of class NSAssertionHandler. When invoked, an assertion handler prints an error message that includes the method and class names (or the function name). It then raises an NSInternalInconsistencyException exception. If condition evaluates to NO, the macro invokes handleFailureInMethod:object:file:lineNumber:description: on the assertion handler for the current thread, passing desc as the description string.

    This macro should be used only within Objective-C methods.

    Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS is defined.

    而且在NSException.h 文件中,我们可以清楚的看到 NSAssert 的宏定义:

     #define NSAssert(condition, desc, ...) \
        do {                \
        __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
        if (!(condition)) {     \
                NSString *__assert_file__ = [NSString stringWithUTF8String:__FILE__]; \
                __assert_file__ = __assert_file__ ? __assert_file__ : @"<Unknown File>"; \
            [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd \
            object:self file:__assert_file__ \
                lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \
        }               \
            __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \
        } while(0)
    

    苹果文档提供了一种禁用Assertions的方法,在实践的过程中我又发现了另外一个禁用NSAssert的方法,详情如下:

    1. 苹果文档:“Build Settings” -> "preprocessor macro" -> 添加“NS_BLOCK_ASSERTIONS” 则禁用了Assertions
    2. 另一种方式:“Build Settings” -> "Other C Flags" -> 添加“-DNS_BLOCK_ASSERTIONS”即可

    原文链接

    相关文章

      网友评论

          本文标题:有关NSAssert相关知识点

          本文链接:https://www.haomeiwen.com/subject/lynnkttx.html