NSAssert和NSParameterAssert

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

https://www.jianshu.com/p/3072e174554f

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 *[email protected]"中山郎";
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;
    }

原文地址:https://www.cnblogs.com/sundaysgarden/p/10354170.html

时间: 2024-12-26 15:18:26

NSAssert和NSParameterAssert的相关文章

NSAssert NSCAssert NSParameterAssert

@这里给介绍几个系统给我们,很方便进行程序调试,定位错误的宏 我们写程序时,对于不放心或容易报错的地方,可以加上这个代码 #define NSAssert(condition, desc, ...) #define NSCAssert(condition, desc, ...) 第一个参数为一个条件判断,如果为假,则抛出异常,显示第二个参数所描述的信息(定义为自己能看的很明白的错误提示信息). 例如: NSString *test = @"HMT"; NSAssert([test is

使用NSAssert()和NSParameterAssert调试程序

NSAssert: NSAssert()只是一个宏,用于开发阶段调试程序中的Bug,通过为NSAssert()传递条件表达式来断定是否属于Bug,满足条件返回真值,程序继续运行,如果返回假值,则抛出异常,并切可以自定义异常描述.NSAssert()是这样定义的: #define NSAssert(condition, desc) condition是条件表达式,值为YES或NO:desc为异常描述,通常为NSString.当conditon为YES时程序继续运行,为NO时,则抛出带有desc描述

断言NSAssert的使用

1. NSAssert 断言(NSAssert)是一个宏,在开发过程中使用NSAssert可以及时发现程序中的问题. NSAssert声明如下: #define NSAssert(condition, desc, ...) condition:条件表达式.条件成立时,运行后面程序:不成立时,抛出带有desc描述的异常信息. desc:异常描述,通常为NSString类型对象.用于描述条件表达式不成立的错误信息和参数的占位符. ...:desc字符串中的参数. 假设我们需要判断变量值是否大于5,我

NSAssert详解

NSAssert是foundation.framework中定义的一个宏:#define NSAssert(condition, desc, ...)第一个参数为一个条件判断,如果为假,则抛出异常,显示第二个参数所描述的信息. 例如:NSAssert(2>=3, @"2>=3 is false!");在debug模式下运行,会终止程序,并抛出如下异常:2013-04-24 09:24:16.618 TestAssertion[825:c07] *** Terminating

IOS中调试的辅助宏 NSAssert

NSAssert函数: 1 NSAssert(condition, desc, ...); 1. condition:条件,如果条件满足则程序正常之行,如果条件不满足则程序崩溃,奔溃的信息可以由后面的desc来打印出来: 实例如下: NSInteger age = 10; NSAssert(age == 01, @"the condition is not right -%s--%s---%d",__FILE__,__FUNCTION__,__LINE__); 这时打印出来的信息为:

NSAssert使用

断言使用:断言的第一个参数为NO时,程序执行到这里时就会崩溃并原文打印第二个参数. @implementation People - (void)eat{    BOOL isB = NO;    if (3 > 4)    {        isB = YES;     }    NSAssert(isB == YES, @"要崩溃了");//断言的第一个参数为NO时,程序执行到这里时就会崩溃并原文打印第二个参数.} @end

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

block和self的相互引用造成的循环引用,想必大家都是明白的.上下面的代码(截取部分) __weak typeof(self) weakSelf = self; self.jsBridgeFunctionDic = @{ JSBridgeCallNativePage: ^(NSDictionary *data){ NSLog(@"JSBridgeCallNativePage"); NSDictionary *params = [data dictionaryForKey:@&quo

NSAssert

首先,NSAssert 是 foundation.framework 框架中的一个宏定义,作为断点检查的条件信息.如果给他一个 false 条件,会生成一个断点检查. NSAssert Generates an assertion if a given condition is false. Declaration 声明 OBJECTIVE-C #define NSAssert(condition, desc, ...) Parameters 参数 condition An expression

NSAssert,NSCassert

在苹果的SDK中可以看到这两个都是定义的宏 NSAssert 的定义如下: #define NSAssert(condition, desc, ...) do { __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS if (!(condition)) { [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd object:self file:[NSString stringWithUTF8String: