专注、坚持

iOS 中的断言

2020.07.27 by kingcos
Date Notes
2020-07-27 首次提交

0

Preface

断言(Assertion)是我们常用于 Debug 时的得力助手,其使得程序得以崩溃在早期,引起我们足够的重视,保障代码质量又不影响用户的体验。本文将简单介绍 iOS 中的断言类型以及使用方式与原理。

assert

NSAssert & NSCAssert

NSAssert

// NSException.h

#if !defined(NS_BLOCK_ASSERTIONS)

#if !defined(_NSAssertBody)
#define NSAssert(condition, desc, ...) \
    do {    \
 __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
 if (__builtin_expect(!(condition), 0)) {  \
            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)
#endif

#if !defined(_NSCAssertBody)
#define NSCAssert(condition, desc, ...) \
    do {    \
 __PRAGMA_PUSH_NO_EXTRA_ARG_WARNINGS \
 if (__builtin_expect(!(condition), 0)) {  \
            NSString *__assert_fn__ = [NSString stringWithUTF8String:__PRETTY_FUNCTION__]; \
            __assert_fn__ = __assert_fn__ ? __assert_fn__ : @"<Unknown Function>"; \
            NSString *__assert_file__ = [NSString stringWithUTF8String:__FILE__]; \
            __assert_file__ = __assert_file__ ? __assert_file__ : @"<Unknown File>"; \
     [[NSAssertionHandler currentHandler] handleFailureInFunction:__assert_fn__ \
  file:__assert_file__ \
      lineNumber:__LINE__ description:(desc), ##__VA_ARGS__]; \
 }    \
        __PRAGMA_POP_NO_EXTRA_ARG_WARNINGS \
    } while(0)
#endif

#else // NS_BLOCK_ASSERTIONS defined

#if !defined(_NSAssertBody)
#define NSAssert(condition, desc, ...) do {} while (0)
#endif

#if !defined(_NSCAssertBody)
#define NSCAssert(condition, desc, ...) do {} while (0)
#endif

#endif

NSParameterAssert

Reference