美文网首页
iOS开发中NSAssert()使用

iOS开发中NSAssert()使用

作者: CoderSJun | 来源:发表于2016-12-19 16:38 被阅读146次

今天在写代码的时候看别人写的代码 看到了他们写了

NSAssert(self.dataSource,@"BHBCenterView`s dataSource was nil.");

于是就查了一些关于NSAssert的资料 记录一下

NSAssert()只是一个宏

用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug,满足条件返回真值,程序继续运行,如果返回假值,则抛出异常,并切可以自定义异常描述。NSAssert()是这样定义的:

#define NSAssert(condition, desc)

condition是条件表达式,值为YES或NO;desc为异常描述,通常为NSString。当conditon为YES时程序继续运行,为NO时,则抛出带有desc描述的异常信息。

生成一个LotteryEntry对象时,传入的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;

}

接下来则是生成对象时传入一个值为nil的NSDate,看断言是否运行。

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

(

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

转自使用断言NSAssert()调试程序错误

通过上面的NSAssert()的报错,很容易就能确定错误发生的原因及位置。

就是

*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Argument must be non-nil'


我们也可以设置断言只在debug的时候打印

设置方法:在Build Settings菜单,找到Preprocessor Macros项,Preprocessor Macros项下面有一个选择,用于程序生成配置:Debug版和Release版。选择 Release项,设置NS_BLOCK_ASSERTIONS,不进行断言检查。

相关文章

  • 断言

    在iOS开发中,可以使用宏NSAssert()在程序中进行断言处理。NSAssert()使用正确,可以帮助开发者尽...

  • iOS开发中NSAssert()使用

    今天在写代码的时候看别人写的代码 看到了他们写了 NSAssert(self.dataSource,@"BHBCe...

  • NSAssert()使用目的

    转自iOS开发中断言的使用—NSAssert()[https://blog.csdn.net/univcore/a...

  • iOS开发NSAssert使用

    NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来判定是否...

  • 断言NSAssert的使用

    1. NSAssert 断言(NSAssert)是一个宏,在开发过程中使用NSAssert可以及时发现程序中的问题...

  • iOS断言(NSAssert)的用法

    NSAssert()介绍 NSAssert()是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()...

  • 使用NSAssert()和NSParameterAssert调试

    NSAssert: NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递...

  • AVPlayer相关笔记

    1.NSAssert NSAssert()是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递...

  • iOS开发中断言的使用—NSAssert()

    NSAssert()是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属...

  • iOS开发 NSAssert(NO, @"attempting

    在使用Mansory添加约束时候,一不留神,报了这个错误 解决方法,查看断点下面这块代码,找到问题所在 tip:遇...

网友评论

      本文标题: iOS开发中NSAssert()使用

      本文链接:https://www.haomeiwen.com/subject/ijepsttx.html