断言(NSAssert)的使用

作者: 小木___Boy | 来源:发表于2016-03-30 20:16 被阅读19133次

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

condition是条件表达式,值为YES或NO;desc为异常描述,通常为NSString。当conditon为YES时程序继续运行,为NO时,则抛出带有desc描述的异常信息。NSAssert()可以出现在程序的任何一个位置。

NSAssert和assert 区别

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

NSAssert/NSCAssert

iOS中用的最多的是两对断言, NSAssert/NSCAssert 和 NSParameterAssert/NSCparameterAssert. 要知道他们的区别,我们先来看看他们定义.

    #if !defined(NS_BLOCK_ASSERTIONS)
    #if !defined(_NSAssertBody)
    #define NSAssert(condition, desc, ...)  \\\\
    do {              \\\\
    __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \\\\
    if (!(condition)) {       \\\\
    [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd \\\\
    object:self file:[NSString stringWithUTF8String:__FILE__] \\\\
    lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \\\\
    }             \\\\
    __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \\\\
    } while(0)
    #endif
    #if !defined(_NSCAssertBody)
    #define NSCAssert(condition, desc, ...) \\\\
    do {              \\\\
    __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \\\\
    if (!(condition)) {       \\\\
    [[NSAssertionHandler currentHandler] handleFailureInFunction:[NSString stringWithUTF8String:__PRETTY_FUNCTION__] \\\\
    file:[NSString stringWithUTF8String:__FILE__] \\\\
    lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \\\\
    }             \\\\
    __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \\\\
    } while(0)
    #endif

从定义可以看出来,前者是适合于ObjectC的方法,_cmd 和 self 与运行时有关. 后者是适用于C的函数。
NSParameterAssert/NSCparameterAssert 两者的区别也是前者适用于Objective-C的方法,后者适用于C的函数。
实际开发中就用前者就可以了。

NSAssert/NSCAssert 和 NSParameterAssert/NSCparameterAssert 的区别是前者是针对条件断言, 后者只是针对参数是否存在的断言, 调试时候可以结合使用,先判断参数,再进一步断言,确认原因.

NSAssert的用法

    int a = 1;
    NSCAssert(a == 2, @"a must equal to 2"); //第一个参数是条件,如果第一个参数不满足条件,就会记录并打印后面的字符串

运行则会崩溃并在控制台输出信息如下:

*** Assertion failure in -[ViewController viewDidLoad](), /Users/yinwentao/Desktop/MYAssert/MYAssert/ViewController.m:32
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'a must equal to 2'

NSParameterAssert的用法

- (void)assertWithPara:(NSString *)str
{
    NSParameterAssert(str); //只需要一个参数,如果参数存在程序继续运行,如果参数为空,则程序停止打印日志
    //further code ...
}

如果 调用方法 assertWithPara: 传入参数为空则有如下日志

*** Assertion failure in -[ViewController assertWithPara:], /Users/yinwentao/Desktop/MYAssert/MYAssert/ViewController.m:45
*** Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'Invalid parameter not satisfying: str'

日志中的数字是告诉你 第多少行代码出错了。

Xcode 已经默认将release环境下的断言取消了, 免除了忘记关闭断言造成的程序不稳定. 所以不用担心 在开发时候大胆使用。

release下是不用担心的.png

自定义NSAssertionHandler

NSAssertionHandler实例是自动创建的,用于处理错误断言。如果 NSAssert和NSCAssert条件评估为错误,会向 NSAssertionHandler实例发送一个表示错误的字符串。每个线程都有它自己的NSAssertionHandler实例。
我们可以自定义处理方法,从而使用断言的时候,控制台输出错误,但是程序不会直接崩溃。

#import "MyAssertHandler.h"

@implementation MyAssertHandler

//处理Objective-C的断言
- (void)handleFailureInMethod:(SEL)selector object:(id)object file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format,...
{
    NSLog(@"NSAssert Failure: Method %@ for object %@ in %@#%li", NSStringFromSelector(selector), object, fileName, (long)line);
}
//处理C的断言
- (void)handleFailureInFunction:(NSString *)functionName file:(NSString *)fileName lineNumber:(NSInteger)line description:(NSString *)format,...
{
    NSLog(@"NSCAssert Failure: Function (%@) in %@#%li", functionName, fileName, (long)line);
}

@end

给线程添加处理类

NSAssertionHandler *myHandler = [[MyAssertHandler alloc] init];
//给当前的线程
[[[NSThread currentThread] threadDictionary] setValue:myHandler
                                               forKey:NSAssertionHandlerKey];

自定义NSAssertionHandler后,程序能够获得断言失败后的信息,但是程序可以继续运行,不会强制退出程序.

相关文章

  • HQ移动20170317期周报

    1. NSAssert() 和 NSCAssert()的使用 NSAssert()用于 OC 语法的断言NSCAs...

  • 断言NSAssert的使用

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

  • 断言

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

  • NSAssert断言的使用

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

  • 断言(NSAssert)的使用

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

  • 断言NSAssert

    NSAssert与assert NSAssert和assert是断言,主要的差别是assert在断言失败的时候只是...

  • NSAssert断言

    NSAssert与assert NSAssert和assert是断言,主要的差别是assert在断言失败的时候只是...

  • NSAssert()使用目的

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

  • iOS一些开发中需要积累的知识

    1.NSAssert 调试的好帮手.断言 Exampe: NSAssert( x != 0, @"an erorr...

  • iOS中的断言

    NSAssert 这个应该都比较熟悉,他的名字叫做“断言”。断言(assertion)是指在开发期间使用的、让程序...

网友评论

  • 埃辛诺斯忍:请问一下,自定义的NSAssertionHandler 之后,使用NSAssert需要配合线程使用,但是NSAssert不一定在哪个线程使用呢,怎么能保证每个线程都支持呢?请问有没有方法呢?
  • 翀鹰精灵: NSAssert(condition, desc, ...);
    NSAssert1(condition, desc, arg1);
    NSAssert2(condition, desc, arg1, arg2);
    NSAssert3(condition, desc, arg1, arg2, arg3);
    NSAssert4(condition, desc, arg1, arg2, arg3, arg4);
    NSAssert5(condition, desc, arg1, arg2, arg3, arg4, arg5);
    _NSAssertBody(condition, desc, arg1, arg2, arg3, arg4, arg5);
    这几种断言的区别是什么?
  • 翀鹰精灵:你好 我想问下,
    NSAssert(<#condition#>, <#desc, ...#>);
    NSAssert1(<#condition#>, <#desc#>, <#arg1#>);
    NSAssert2(<#condition#>, <#desc#>, <#arg1#>, <#arg2#>);
    NSAssert3(<#condition#>, <#desc#>, <#arg1#>, <#arg2#>, <#arg3#>);
    NSAssert4(<#condition#>, <#desc#>, <#arg1#>, <#arg2#>, <#arg3#>, <#arg4#>);
    NSAssert5(<#condition#>, <#desc#>, <#arg1#>, <#arg2#>, <#arg3#>, <#arg4#>, <#arg5#>);
    _NSAssertBody(<#condition#>, <#desc#>, <#arg1#>, <#arg2#>, <#arg3#>, <#arg4#>, <#arg5#>);
    这几种断言有什么区别呢 ?
    我的代码得优化:@iDog 这些arg 是参数,就是为了将你的desc 描述的更加准确 你看看这个https://stackoverflow.com/questions/5496378/what-is-nsassert1
    iDog:@我的代码得优化 你好 可以麻烦解释一下神秘叫对描述的论证吗 我不是很理解这句话
    我的代码得优化:@翀鹰女孩
    arg1是对描述的论证

本文标题:断言(NSAssert)的使用

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