NSAssert断言

今天运行代码遇到了NSAssert断言,这里做一个学习记录。

形式

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

官方文档链接

作用

在condition为false的时候产生断言。

示例

代码

@interface MyObject : NSObject

- (void) show;
@end

@implementation MyObject
- (void) show {
    NSAssert(NO,@"Some Exception");
}
@end


int main(int argc, const char * argv[]) {
    @autoreleasepool {
        // insert code here...
        NSLog(@"Hello, World!");
        MyObject* obj = [MyObject new];
        [obj show];
    }
    return 0;
}

输出

Test[13846:14728820] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Some Exception'
*** First throw call stack:
(
0   CoreFoundation                      0x00007fff531da2fb __exceptionPreprocess + 171
1   libobjc.A.dylib                     0x00007fff79b4bc76 objc_exception_throw + 48
2   CoreFoundation                      0x00007fff531e0092 +[NSException raise:format:arguments:] + 98
3   Foundation                          0x00007fff552bc690 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 193
4   Test                                0x0000000100000d8a -[MyObject show] + 234
5   Test                                0x0000000100000e25 main + 101
6   libdyld.dylib                       0x00007fff7a73a145 start + 1
7   ???                                 0x0000000000000001 0x0 + 1
)
libc++abi.dylib: terminating with uncaught exception of type NSException

说明

从输出可见,在condition为false的时候,抛出了NSInternalInconsistencyException异常,由于该异常未处理,程序退出。

宏定义原型

#if !defined(NS_BLOCK_ASSERTIONS)

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

从定义中可见:

  • NSAssert是否生效受宏定义NS_BLOCK_ASSERTIONS控制。
  • condition为false时会调用NSAssertionHandler处理过程的handleFailureInMethod方法,并将现场的文件名、代码行号、用户自定义信息作为参数传入。每个线程都可定义其自身的NSAssertionHandler,如例子所展示,当NSAssertionHandler被调用时,会输出现场相关信息,并抛出‘NSInternalInconsistencyException’异常。如何注册自己的异常处理过程,这篇文章非常详细,这里就不赘述了。
  • 由于有object:self参数,可见该方法只能在Object-C方法中被使用。

其他说明:

  • 千万千万不要在NSAssert里也有意义的代码。因为release版本大多会默认禁用NSAssert。曾经就定位过这个原因造成的debug功能正常,release就不正常的问题。
  • 如果需要在C方法中实现断言,请用NSCAssert

参考

https://developer.apple.com/documentation/foundation/nsassert
http://nshipster.cn/nsassertionhandler/

你可能感兴趣的:(NSAssert断言)