标签:
UI 控件懒加载问题:
1, 什么时候使用懒加载加载UI控件?
2, 加载控件的什么属性?
3, 用什么类型的指针修饰控件?
code : (ARC)
定义属性,
@property(nonatomic,weak) UIButton *customBtn1;
重写getter方法
-(UIButton *)customBtn1{
if (_customBtn1 == nil) {
_customBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
}
return _customBtn1;
}
在这个控制器中这个控件一定会用到,但是不知道什么时候会用到,这时候来个懒加载加载UI控件是可以的,
这个时候就遇到了一个棘手的问题,
我定义属性的时候用的是 weak或者assign , getter方法能够返回这个弱类型的指针吗?
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
self.customBtn1.frame = CGRectMake(100, 100, 100, 50);
[self.view addSubview:self.customBtn1];
[self.customBtn1 setTitle:@"customBtn1" forState:UIControlStateNormal];
[self.customBtn1 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.customBtn1 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[self.customBtn1 addTarget:self action:@selector(testBtn1Click) forControlEvents:UIControlEventTouchUpInside];
}
- (void)testBtn1Click {
NSLog(@"---testBtn1Click---");
}
console :
2015-06-24 12:46:15.333 test001[2811:245716] ---testBtn1Click---
答案貌似是可以的,
但是:
-(UIButton *)customBtn1{
if (_customBtn1 == nil) {
// _customBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
_customBtn1 = [[UIButton alloc] init];
}
return _customBtn1;
}
如果创建按钮的时候用的不是类方法,用alloc init 创建的按钮是有问题的,
在ARC下 这个按钮一经创建就会被销毁,弱指针的地址不能够返回,
再比如:
UIImageView:
@property(nonatomic,weak) UIImageView *customImageView;
一经创建就会被销毁;
所以,UI控件用懒加载的方式创建的话,最好用strong修饰
code:
- (UIButton *)curstomBtn2{
if (_curstomBtn2 == nil) {
_curstomBtn2 = [[UIButton alloc] init];
[_curstomBtn2 setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[_curstomBtn2 setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted];
[_curstomBtn2 setTitle:@"这是用strong修饰的控件" forState:UIControlStateNormal];
_curstomBtn2.frame = CGRectMake(100, 200, 150, 40);
}
return _curstomBtn2;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.curstomBtn2];
[self.curstomBtn2 addTarget:self action:@selector(testBtn2Click) forControlEvents:UIControlEventTouchUpInside];
}
- (void)testBtn2Click {
NSLog(@"---testBtn2Click---");
}
imageView中:
@interface SAMFourViewController ()
/**
* 自定义的imageView属性
*/
@property(nonatomic,strong) UIImageView *customImageView;
@end
@implementation SAMFourViewController
- (UIImageView *)customImageView{
if (_customImageView == nil) {
_customImageView = [[UIImageView alloc] initWithFrame:(CGRect){10,70,300,300}];
}
return _customImageView;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [UIColor whiteColor];
[self.view addSubview:self.customImageView];
self.customImageView.image = [UIImage imageNamed:@"asa"];
}
@end
运行结果:
ARC下 UI控件用assign的后果:
@property (nonatomic, assign) UIButton *btn2;
self.btn2 = [[UIButton alloc] initWithFrame:(CGRect){20,30,100,40}];[self.view addSubview:self.btn2];
这个就是传说中的野指针错误!!!!
标签:
原文地址:http://www.cnblogs.com/wolfman4secret/p/4602565.html