初学oc
,在网上我看到了strong
和weak
的解释:只要有一个强引用还未被释放,就算把所有弱引用释放了,这个引用也不会被释放。
但是我想问怎么创建一个只有弱引用的变量,如果创建了,会发生什么情况。
我在学习中遇到过一个问题,
@interface ViewController ()
// 我用声明了一个弱引用属性 一个label标签
@property (weak, nonatomic) UILabel *label;
@end
@implementation ViewController
CGFloat labelWidh = 85;
CGFloat labelHeight = 34;
CGFloat labelTopView = 454;
CGRect labelFrame = CGRectMake((screen.size.width - labelWidh) / 2, labelTopView, labelWidh, labelHeight);
// 在这里,编辑器会发出警告
// Assigning retained object to weak property; object will be released after assignment
self.label = [[UILabel alloc] initWithFrame: labelFrame];
self.label.text = @"code label";
self.label.textAlignment = NSTextAlignmentCenter;
[self.view addSubview:self.label];
@end
实际运行会发现,label
并没有出现在视图上。
在警告之前打断点会发现,定义的label
属性早已变成了nil
,我的猜测是由于一开始就是弱引用,没有强引用,所以就自动被释放了。不知道对不对,还请大佬们解释解释