1.從storyboard或者xib拖的控件
從storyboard或者xib拖的控件是用weak修飾火鼻,此時storyboard/xib對button是強引用,所以代碼聲明的屬性對它弱引用就可以了雕崩。
@property(nonatomic,weak) IBOOutlet UIButton *button;
2.代碼聲明的UI控件
2.1 weak修飾
OC中如果對象創(chuàng)建后沒有強引用會被自動釋放魁索,所以下面這種方式創(chuàng)建的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];
}
我們可以先創(chuàng)建一個局部的控件(局部變量默認(rèn)是強引用的)粗蔚,然后在讓weak修飾的UI控件指向這個局部控件,就可以達到我們想要的效果饶火。weak修飾的UI控件removeFromSuperview
后引用計數(shù)變?yōu)?支鸡,所以會立馬銷毀冬念。
@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修飾的話就不需要先創(chuàng)建局部的控件趁窃。當(dāng)執(zhí)行[self.view addSubview:self.button];
后控件的引用計數(shù)是2牧挣,當(dāng)[self.button removeFromSuperview];
后控件的引用計數(shù)變?yōu)?,因為控制器還持有這個控件醒陆,所以這個控件并不會銷毀瀑构,當(dāng)控制器銷毀時這個控件才會銷毀。
@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];
}