1.从storyboard或者xib拖的控件
从storyboard或者xib拖的控件是用weak修饰,此时storyboard/xib对button是强引用,所以代码声明的属性对它弱引用就可以了。
@property(nonatomic,weak) IBOOutlet UIButton *button;
2.代码声明的UI控件
2.1 weak修饰
OC中如果对象创建后没有强引用会被自动释放,所以下面这种方式创建的button还没来得及添加到self.view中就立马会被释放,达不到我们想要的效果。
@property (nonatomic , weak) UIButton *button;
- (void)createButton{
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
self.button.frame = CGRectMake(10, 10, 100, 30);
[self.view addSubview:self.button];
}
我们可以先创建一个局部的控件(局部变量默认是强引用的),然后在让weak修饰的UI控件指向这个局部控件,就可以达到我们想要的效果。weak修饰的UI控件removeFromSuperview
后引用计数变为0,所以会立马销毁。
@property (nonatomic , weak) UIButton *button;
- (void)createButton{
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
btn.frame = CGRectMake(10, 10, 100, 30);
self.button = btn;
[self.view addSubview:self.button];
}
2.2 strong修饰
如果是用strong修饰的话就不需要先创建局部的控件。当执行[self.view addSubview:self.button];
后控件的引用计数是2,当[self.button removeFromSuperview];
后控件的引用计数变为1,因为控制器还持有这个控件,所以这个控件并不会销毁,当控制器销毁时这个控件才会销毁。
@property (nonatomic , strong) UIButton *button;
- (void)createButton{
self.button = [UIButton buttonWithType:UIButtonTypeCustom];
self.button.frame = CGRectMake(10, 10, 100, 30);
[self.view addSubview:self.button];
}
网友评论