【轉】使用斷言NSAssert()偵錯工具錯誤

來源:互聯網
上載者:User

標籤:

NSAssert()只是一個宏,用於開發階段偵錯工具中的Bug,通過為NSAssert()傳遞條件運算式來斷定是否屬於Bug,滿足條件返回真值,程式繼續運行,如果返回假值,則拋出異常,並切可以自訂異常描述。NSAssert()是這樣定義的:

#define NSAssert(condition, desc)

condition是條件運算式,值為YES或NO;desc為異常描述,通常為NSString。當conditon為YES時程式繼續運行,為NO時,則拋出帶有desc描述的異常資訊。NSAssert()可以出現在程式的任何一個位置。具體案例如下:

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


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

    self =[super init];

    if (self){

      NSAssert(theDate!= nil, @"Argument must benon-nil");

       entryDate =theDate;

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

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

    }

   return  self;

}

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

 

LotteryEntry *nilEntry =[[LotteryEntry alloc] initWithEntryDate:nil];

斷言效果如下:


2013-01-17 20:49:12.486 lottery[3951:303] *** Terminating appdue 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 +[NSExceptionraise:format:arguments:] + 104

3   Foundation                     0x00007fff88dae6a2 -[NSAssertionHandlerhandleFailureInMethod:object:file:lineNumber:description:] +189

4   lottery                        0x0000000100001929 -[LotteryEntryinitWithEntryDate:] + 249

5   lottery                        0x0000000100001794 main + 932

6   libdyld.dylib                   0x00007fff8d83f7e1 start + 0

)

libc++abi.dylib: terminate called throwing an exception

 

【轉】使用斷言NSAssert()偵錯工具錯誤

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.