您的位置:首页 > 移动开发 > IOS开发

iOS断言-抛异常

2015-12-28 11:56 621 查看
自定义描述异常信息的desc就是所谓的抛异常

注意: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))
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: