在开发中,常常会遇到传参的情况,这时候就需要对参数进行有效判断,以保证传递的参数是真实有效的。
而在判断时,通常的方法无非就是if...else...之类的使用。
其实在开发阶段为了保证参数有真实有效性,我们还可以使用断言进行参数的异常处理。
常用的断言有NSAssert、NSParameterAssert。
NSAssert和NSParameterAssert的都是系统宏定义。
#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)
#endif
#define NSParameterAssert(condition) NSAssert((condition), @"Invalid parameter not satisfying: %@", @#condition)
// 方法1
NSAssert(self.hostUrl.host != nil, @"self.hostUrl must be non-nil");
// 方法2
NSParameterAssert(self.hostUrl.host);
在开发阶段使用了断言后,如果参数异常且在模拟器上运行时则会直接导致应用程序闪退,而如果在真机设备上运行则不会闪退。