2016.05.05 18:34* 字数 861 阅读 5127评论 0喜欢 17

NSAssert和NSParameterAssert在开发环境中经常被使用,调试和验证代码参数的完整性,断言为真,则表明程序运行正常,而断言为假,则意味着它已经在代码中发现了意料之外的错误。xCode中的断言在Debug模式默认是开启的,Realse版本中是禁用的.

基础断言

基础类库中了两种断言,NSAssert和NSParameterAssert是OC断言,NSCAssert和NSCParameterAssert是C语言断言。先来看一下NSAssert定义:
<pre><code>The NSAssert macro evaluates the condition and serves as a front end to the assertion handler. Each thread has its own assertion handler, which is an object of class NSAssertionHandler. When invoked, an assertion handler prints an error message that includes the method and class names (or the function name). It then raises an NSInternalInconsistencyException exception. If condition evaluates to NO, the macro invokes handleFailureInMethod:object:file:lineNumber:description: on the assertion handler for the current thread, passing desc as the description string. This macro should be used only within Objective-C methods. Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS is defined. **Important:Important** Do not call functions with side effects in the condition parameter of this macro. The condition parameter is not evaluated when assertions are disabled, so if you call functions with side effects, those functions may never get called when you build the project in a non-debug configuration. **Note:Note** Not all release configurations disable assertions by default.</code></pre>
NSParameterAssert的定义:
<pre>Assertions evaluate a condition and, if the condition evaluates to false, call the assertion handler for the current thread, passing it a format string and a variable number of arguments. Each thread has its own assertion handler, which is an object of class NSAssertionHandler. When invoked, an assertion handler prints an error message that includes method and class names (or the function name). It then raises an NSInternalInconsistencyException exception. This macro validates a parameter for an Objective-C method. Simply provide the parameter as the condition argument. The macro evaluates the parameter and, if it is false, it logs an error message that includes the parameter and then raises an exception. Assertions are disabled if the preprocessor macro NS_BLOCK_ASSERTIONS is defined. All assertion macros return void. **Important:Important** Do not call functions with side effects in the condition parameter of this macro. The condition parameter is not evaluated when assertions are disabled, so if you call functions with side effects, those functions may never get called when you build the project in a non-debug configuration. **Note:Note** Not all release configurations disable assertions by default.</pre>
两者的定义类似,大概意思就是如果是false就会调用当前线程Assertion Hanlder进行处理,非Debug模式下可能所有的断言都不会调用,最后一句很重要,并不是所有的发布配置会禁用断言,如果想看断言是否禁用,需要看一下设置:

 
Snip20160505_1.png

简单测试:
<pre><code>`
NSString *result=@"中山郎";
NSInteger count=10;
NSAssert(count>10, @"总数必须大于10");
NSLog(@"断言执行之后");

</code></pre> 崩溃信息: <pre><code>
** FECategory[23811:248235] *** Assertion failure in -[ViewController setupAssert], /ViewController.m:45**
** FECategory[23811:248235] *** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '****总数必须大于****10'**`</code></pre>

NSAssertionHandler

NSAssert异常处理的时候默认是NSAssertionHandler处理的,不过我们可以自定自己的Handler,实现两个方法:
<pre><code>`

  • (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(nullable NSString *)format,... NS_FORMAT_FUNCTION(5,6);
  • (void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(nullable NSString *)format,... NS_FORMAT_FUNCTION(4,5);`</code></pre>

handleFailureInMethod处理OC方法中的断言,handleFailureInFunction处理C函数中的断言
自定义继承自NSAssertionHandler的类FEAssertionHandler:
<pre><code>`
@implementation FEAssertionHandler

-(void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format, ...{
NSLog(@"FlyElephant-FEAssertionHandler: Method %@ for object %@ in %@--line:%li", NSStringFromSelector(selector), object, fileName, (long)line);
}

-(void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format, ...{
NSLog(@"FlyElephant-FEAssertionHandler:Function (%@) in %@--line:%li", functionName, fileName, (long)line);
}

@end
</code></pre> AppDelegate中设置断言处理: <pre><code>

  • (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    FEAssertionHandler *hanlder=[[FEAssertionHandler alloc]init];
    [[[NSThread currentThread] threadDictionary] setValue:hanlder forKey:NSAssertionHandlerKey];
    return YES;
    }

NSAssert和NSParameterAssert的更多相关文章

  1. iOS-----程序异常处理----- 断言NSAssert()和NSParameterAssert区别和用处

    NSAssert和assert是断言,主要的差别是assert在断言失败的时候只是简单的终止程序,而NSAssert会报告出错误信息并且打印出来.所以尽管的使用NSAssert,可以不去使用asser ...

  2. 使用NSAssert()和NSParameterAssert调试程序

    NSAssert: NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug,满足条件返回真值,程序继续运行,如果返回假值,则抛出异 ...

  3. iOS 开发知识小集(1)

    iOS 开发知识小集(1) 2015-05-15  iOS大全 (点击上方蓝字,快速关注我们) 一直想做这样一个小册子,来记录自己平时开发.阅读博客.看书.代码分析和与人交流中遇到的各种问题.之前有过 ...

  4. iOS 开发中的 Tips(一)

    背景 学习6个小Tips 那就跟我一起学习小知识点吧.目录如下: 修改Mac终端(Terminal)里不同类型文件的显示颜色 修改Mac终端(Terminal)的提示文字 Mac终端显示/隐藏文件命令 ...

  5. iOS 10开发NSAssert(断言)的使用

    断言(NSAssert)的使用 字数1055 阅读3270 评论3 喜欢30 NSAssert()是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug ...

  6. 断言--NSAssert

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

  7. 什么是NSAssert?

    断言, 判断是否符合某个特定条件, 符合就继续运行程序, 反之就抛出异常, 后面为自定义错误提示, 也可以使用NSParameterAssert, 在调试上有着很大的方便 int a = 0; NSA ...

  8. 断言NSAssert的使用

    1. NSAssert 断言(NSAssert)是一个宏,在开发过程中使用NSAssert可以及时发现程序中的问题. NSAssert声明如下: #define NSAssert(condition, ...

  9. 小心一些,断言可能让你的造成循环引用NSAssert

    block和self的相互引用造成的循环引用,想必大家都是明白的.上下面的代码(截取部分) __weak typeof(self) weakSelf = self; self.jsBridgeFunc ...

随机推荐

  1. SQL Server DATA文件夹下audittrace20180124152845_52.trc类文件异常增多

    同事告知某现场SQL Server2008R2数据库的DATA文件夹下audittrace开头的trc文件不断增多,占用较大空间,因此需要关停,尝试解决步骤如下: 1.查看是否有后台开启的trace ...

  2. 使用Navicat for Mysql连接mysql服务器

    使用Navicat for Mysql连接mysql服务器 在windows上用Navicat for Mysql 连接装在虚拟机Ubuntu上的mysql服务器时出现的问题的解决方案. Navica ...

  3. python爬虫之天气预报网站--查看最近(15天)的天气信息(正则表达式)

    python爬虫之天气预报网站--查看最近(15天)的天气信息(正则表达式) 思路: 1.首先找到一个自己想要查看天气预报的网站,选择自己想查看的地方,查看天气(例:http://www.tianqi ...

  4. 通用Logging框架设计

    项目开发中,大家都会使用日志框架(LogBack, log4j , java.util.logging 等).下面来简单的了解一下日志框架的大体设计思路. 类图:

  5. 【算法】LeetCode算法题-Count And Say

    这是悦乐书的第153次更新,第155篇原创 01 看题和准备 今天介绍的是LeetCode算法题中Easy级别的第12题(顺位题号是38).count-and-say序列是整数序列,前五个术语如下: ...

  6. Java Native Interface(JNI)

    JNI能让Java代码在Java虚拟机里调用其他编程语言(例如C.C++)写的应用或库,且不会影响任何Java虚拟机的实现. 什么时候用JNI? 1.应用程序所需的平台相关功能,标准的Java类库不支 ...

  7. Go学习笔记06-内建容器

    Go学习笔记06-内建容器 Go语言 数组 *切片(Slice) #F44336 Slice的操作 Map map示例 字符处理 数组 定义数组: //这样定义数组编译器自动初始化每个元素为0  va ...

  8. Python 简易版选课系统

    一.创建学生类 # # 创建学生类 import random class Student: def __init__(self,num,name,address,course_lst=None): ...

  9. chrome的source工具

    http://www.cnblogs.com/ys-ys/p/5597717.html http://www.cnblogs.com/strick/p/5556434.html

  10. 设计模式のFlyweight(享元模式)----结构模式

    一.产生背景 享元模式:它使用共享物件,用来尽可能减少内存使用量以及分享资讯给尽可能多的相似物件:它适合用于只是因重复而导致使用无法令人接受的大量内存的大量物件.通常物件中的部分状态是可以分享.常见做 ...