注意:assert是一个宏,只在debug版本中起作用,在release版本中,该语句是不起任何作用的。
示例一:给Label属性赋值不能为空,添加断言,如果为空,则直接crash,抛异常
<pre name="code" class="objc">#import "MainViewController.h"
@interface MainViewController ()
@property(nonatomic,weak)UILabel *lb_title;
@end
@implementation MainViewController
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *lable = [[UILabel alloc]initWithFrame:CGRectMake(10, 200, 100, 30)];
[self.view addSubview:lable];
self.lb_title = lable;
self.lb_title.text = @"";
}
- (void)setLb_title:(UILabel *)lb_title{
NSAssert(lb_title.text !=nil, @"标题不能为空");
_lb_title = lb_title;
}- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
BOOL isOn = NO;
NSAssert(isOn, @"如果表达式是假,直接报错");
}利用宏自定义断言
#define DXAssertNil(a,b,...) NSAssert((a)==nil,(b))
#define DXAssertNotNil(a,b,...) NSAssert((a)!=nil,(b))
#define DXAssertTrue(a,b,...) NSAssert((a),(b))
#define DXAssertEquals(a,b,c,...) NSAssert((a==b),(c))
#define DXAssertNotEquals(a,b,c,...) NSAssert((a!=b),(c))
5378




被折叠的 条评论
为什么被折叠?



