有关NSAssert相关知识点

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

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”即可

原文链接

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容