今天運(yùn)行代碼遇到了NSAssert斷言蚕愤,這里做一個(gè)學(xué)習(xí)記錄凡橱。
形式
#define NSAssert(condition, desc, ...)
作用
在condition為false的時(shí)候產(chǎn)生斷言慰枕。
示例
代碼
@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
說(shuō)明
從輸出可見(jiàn)呛踊,在condition為false的時(shí)候砾淌,拋出了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__ : @"<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)
#endif
從定義中可見(jiàn):
- NSAssert是否生效受宏定義NS_BLOCK_ASSERTIONS控制。
- condition為false時(shí)會(huì)調(diào)用NSAssertionHandler處理過(guò)程的handleFailureInMethod方法愉择,并將現(xiàn)場(chǎng)的文件名劫乱、代碼行號(hào)、用戶自定義信息作為參數(shù)傳入锥涕。每個(gè)線程都可定義其自身的NSAssertionHandler衷戈,如例子所展示,當(dāng)NSAssertionHandler被調(diào)用時(shí)层坠,會(huì)輸出現(xiàn)場(chǎng)相關(guān)信息殖妇,并拋出‘NSInternalInconsistencyException’異常。如何注冊(cè)自己的異常處理過(guò)程破花,這篇文章非常詳細(xì)谦趣,這里就不贅述了。
- 由于有object:self參數(shù)旧乞,可見(jiàn)該方法只能在Object-C方法中被使用蔚润。
其他說(shuō)明:
- 千萬(wàn)千萬(wàn)不要在NSAssert里也有意義的代碼。因?yàn)閞elease版本大多會(huì)默認(rèn)禁用NSAssert尺栖。曾經(jīng)就定位過(guò)這個(gè)原因造成的debug功能正常嫡纠,release就不正常的問(wèn)題。
- 如果需要在C方法中實(shí)現(xiàn)斷言延赌,請(qǐng)用NSCAssert
參考
https://developer.apple.com/documentation/foundation/nsassert
http://nshipster.cn/nsassertionhandler/