有关NSAssert相关知识点

本文详细介绍了Objective-C中的NSAssert宏,包括其定义、参数说明及工作原理。此外还提供了两种禁用NSAssert的方法。

苹果官方文档写的比较清楚:

NSAssert

Generates an assertion if a given condition is false.

Declaration

#define NSAssert(condition, desc, ...)

Parameters

condition:An expression that evaluates to YES or NO

desc: An NSString object that contains a printf-style string containing an error message describing the failure condition and placeholders for the arguments

...:The arguments displayed in the desc string

Discussion

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.

而且在NSException.h 文件中,我们可以清楚的看到 NSAssert 的宏定义:

 #define NSAssert(condition, desc, ...) \
    do {                \
    __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
    if (!(condition)) {     \
            NSString *__assert_file__ = [NSString stringWithUTF8String:__FILE__]; \
            __assert_file__ = __assert_file__ ? __assert_file__ : @"<Unknown File>"; \
        [[NSAssertionHandler currentHandler] handleFailureInMethod:_cmd \
        object:self file:__assert_file__ \
            lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \
    }               \
        __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \
    } while(0)

苹果文档提供了一种禁用Assertions的方法,在实践的过程中我又发现了另外一个禁用NSAssert的方法,详情如下:

  1. 苹果文档:“Build Settings” -> "preprocessor macro" -> 添加“NS_BLOCK_ASSERTIONS” 则禁用了Assertions
  2. 另一种方式:“Build Settings” -> "Other C Flags" -> 添加“-DNS_BLOCK_ASSERTIONS”即可

转载于:https://www.cnblogs.com/Qingbo/p/5237348.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值