今天在寫代碼的時(shí)候看別人寫的代碼 看到了他們寫了
NSAssert(self.dataSource,@"BHBCenterView`s dataSource was nil.");
于是就查了一些關(guān)于NSAssert的資料 記錄一下
NSAssert()只是一個(gè)宏
用于開發(fā)階段調(diào)試程序中的Bug,通過為NSAssert()傳遞條件表達(dá)式來斷定是否屬于Bug跨琳,滿足條件返回真值痹仙,程序繼續(xù)運(yùn)行,如果返回假值,則拋出異常,并切可以自定義異常描述。NSAssert()是這樣定義的:
#define NSAssert(condition, desc)
condition是條件表達(dá)式茂嗓,值為YES或NO;desc為異常描述科阎,通常為NSString述吸。當(dāng)conditon為YES時(shí)程序繼續(xù)運(yùn)行,為NO時(shí)锣笨,則拋出帶有desc描述的異常信息蝌矛。
生成一個(gè)LotteryEntry對象時(shí),傳入的NSDate不能為nil票唆,加入NSAssert()判斷朴读。對象初始化源碼如下:
- (id)initWithEntryDate:(NSDate*)theDate {
self= [superinit];
if(self) {
NSAssert(theDate !=nil,@"Argument must be non-nil");
entryDate= theDate;
firstNumber= (int)random() %100+1;
secondNumber= (int)random() %100+1;
}
returnself;
}
接下來則是生成對象時(shí)傳入一個(gè)值為nil的NSDate屹徘,看斷言是否運(yùn)行走趋。
LotteryEntry*nilEntry = [[LotteryEntryalloc]initWithEntryDate:nil];
斷言效果如下 運(yùn)行程序會(huì)拋出異常:
2013-01-17 20:49:12.486 lottery[3951:303] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Argument must be non-nil'
*** First throw call stack:
(
0CoreFoundation0x00007fff90c590a6 __exceptionPreprocess + 198
1libobjc.A.dylib0x00007fff8fd2a3f0 objc_exception_throw + 43
2CoreFoundation0x00007fff90c58ee8 +[NSException raise:format:arguments:] + 104
3Foundation0x00007fff88dae6a2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4lottery0x0000000100001929 -[LotteryEntry initWithEntryDate:] + 249
5lottery0x0000000100001794 main + 932
6libdyld.dylib0x00007fff8d83f7e1 start + 0
)
libc++abi.dylib: terminate called throwing an exception
轉(zhuǎn)自使用斷言NSAssert()調(diào)試程序錯(cuò)誤
通過上面的NSAssert()的報(bào)錯(cuò),很容易就能確定錯(cuò)誤發(fā)生的原因及位置噪伊。
就是
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Argument must be non-nil'
我們也可以設(shè)置斷言只在debug的時(shí)候打印
設(shè)置方法:在Build Settings菜單簿煌,找到Preprocessor Macros項(xiàng),Preprocessor Macros項(xiàng)下面有一個(gè)選擇鉴吹,用于程序生成配置:Debug版和Release版姨伟。選擇 Release項(xiàng),設(shè)置NS_BLOCK_ASSERTIONS豆励,不進(jìn)行斷言檢查夺荒。