当不使用界面构建器时,我总是对UI元素保持强引用:
@interface myViewController : UIViewController
@property (nonatomic, strong) UILabel *folderLabel;
然后像这样添加它们:
[self.view addSubview self.folderLabel];
因此初始化者是:
-(UILabel *)folderLabel{
if(!_folderLabel) {
_folderLabel = [[UILabel alloc] init];
_folderLabel.text = @"foo";
}
return _folderLabel
}
我被告知,由于某种原因,这是不好的,他们应该总是很弱..
@property (nonatomic, weak) UILabel *folderLabel;
-(UILabel *)folderLabel{
if(!_folderLabel) {
UIlabel *folderLabel = [[UILabel alloc] init];
folderLabel.text = @"foo";
[self.view addSubview:folderLabel];
_folderLabel = folderLabel;
}
return _folderLabel
}
强引用在这里是件坏事吗?
答案 0 :(得分:0)
将子视图添加到self.view时,会保留该视图。一种有效的模式是分配子视图并将其存储在局部变量中,将其添加到self.view然后将其分配给ivar。