readnnly的Property应用
如果我想自定义一个View,里面包含一个Label和一个Button,外界可以修改Label和Button的样式,如何定义
@property (nonatomic, strong) UIButton *button;
@property (nonatomic, strong) UILabel *label;
如果按照上文定义,因为存在Set函数,所以说可以用外界实例化的button和label进行Set,可能会影响到内部的处理,为了保护button和label不被更改,需要声明readonly
@property (nonatomic, strong, readonly) UIButton *button;
@property (nonatomic, strong, readonly) UILabel *label;
声明了readonly之后,虽然button和label无法通过Set更改,但是由于label本身的title这个属性不是readonly的,所以仍然可以更改
[view.label setTitle:@"change"];
但是这样就不行
[view setLabel:label];
结论
Property的readonly并不会传递,声明为readonly的property如果还有下一级property不为readonly,下一级的property还是可以改变的
系统自带的例子
UIButton里的image和label,就是利用这个原理