【轉】使用斷言NSAssert()調試程序錯誤

NSAssert()只是一個宏,用於開發階段調試程序中的Bug,經過爲NSAssert()傳遞條件表達式來判定是否屬於Bug,知足條件返回真值,程序繼續運行,若是返回假值,則拋出異常,並切能夠自定義異常描述。NSAssert()是這樣定義的:

#define NSAssert(condition, desc)c++

condition是條件表達式,值爲YES或NO;desc爲異常描述,一般爲NSString。當conditon爲YES時程序繼續運行,爲NO時,則拋出帶有desc描述的異常信息。NSAssert()能夠出如今程序的任何一個位置。具體事例以下:app

生成一個LotteryEntry對象時,傳入的NSDate不能爲nil,加入NSAssert()判斷。對象初始化源碼以下:dom


- (id)initWithEntryDate:(NSDate *)theDate {spa

    self = [super init];3d

    if (self) {調試

        NSAssert(theDate != nil, @"Argument must be non-nil");orm

        entryDate = theDate;對象

        firstNumber = (int)random() % 100 + 1;ip

        secondNumber = (int)random() % 100 + 1;ci

    }

    return  self;

}

接下來則是生成對象時傳入一個值爲nil的NSDate,看斷言是否運行。

 

LotteryEntry *nilEntry = [[LotteryEntry allocinitWithEntryDate: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

相關文章
相關標籤/搜索