NSAssert()只是一個(gè)宏,用于開發(fā)階段調(diào)試程序中的Bug,通過為NSAssert()傳遞條件表達(dá)式來(lái)斷定是否屬于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描述的異常信息。NSAssert()可以出現(xiàn)在程序的任何一個(gè)位置。具體事例如下:
生成一個(gè)LotteryEntry對(duì)象時(shí),傳入的NSDate不能為nil,加入NSAssert()判斷。對(duì)象初始化源碼如下:
- (id)initWithEntryDate:(NSDate *)theDate {
self = [super init];
if (self) {
NSAssert(theDate != nil, @"Argument must be non-nil");
entryDate = theDate;
firstNumber = (int)random() % 100 + 1;
secondNumber = (int)random() % 100 + 1;
}
return? self;
}
接下來(lái)則是生成對(duì)象時(shí)傳入一個(gè)值為nil的NSDate,看斷言是否運(yùn)行。
LotteryEntry *nilEntry = [[LotteryEntry alloc] initWithEntryDate:nil];
斷言效果如下:
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:
(
0? CoreFoundation? ? ? ? ? ? ? ? ? ? ? 0x00007fff90c590a6 __exceptionPreprocess + 198
1? libobjc.A.dylib? ? ? ? ? ? ? ? ? ? 0x00007fff8fd2a3f0 objc_exception_throw + 43
2? CoreFoundation? ? ? ? ? ? ? ? ? ? ? 0x00007fff90c58ee8 +[NSException raise:format:arguments:] + 104
3? Foundation? ? ? ? ? ? ? ? ? ? ? ? ? 0x00007fff88dae6a2 -[NSAssertionHandler handleFailureInMethod:object:file:lineNumber:description:] + 189
4? lottery? ? ? ? ? ? ? ? ? ? ? ? ? ? 0x0000000100001929 -[LotteryEntry initWithEntryDate:] + 249
5? lottery? ? ? ? ? ? ? ? ? ? ? ? ? ? 0x0000000100001794 main + 932
6? libdyld.dylib? ? ? ? ? ? ? ? ? ? ? 0x00007fff8d83f7e1 start + 0
)
libc++abi.dylib: terminate called throwing an exception