假设我想将UILabel添加到控制器(使用IB).我会有这样的东西我* .h文件:
@property (nonatomic,weak) IBOutlet UILabel * label;
而且我不需要在* .m文件中做更多的事情.但是,如果我删除* .xib文件并尝试设置我的UILabel,例如,init方法之一,如下所示:
self.label = [[UILabel alloc] initWithFrame:CGRectMake(0,100,20)]; self.label.text = @"some text"; [self.view addSubview:self.label];
@property (nonatomic,strong) UILabel * label;
现在,我知道弱和强之间的区别,但我不知道为什么我们在使用IB时可以使用弱的ui元素?有些东西必须保持对这些元素的强烈指示,对吧?但是什么?在第二种情况下,它是控制器,但我不明白它在第一种情况下的行为.
解决方法
Something must keep a strong pointers to these elements,right? But what??
正确,您必须至少有一个对象的强引用才能存在.你只需要对UI的根级对象有一个强引用,这下面的任何东西都可能很弱(因为父对象将拥有它们的子级).与其文件所有者协调的.xib文件将为您完成此操作.
见this document on the workings of xib
files.具体来说,这个snippit:
You typically need strong references to top-level objects to ensure that they are not deallocated; you don’t need strong references to objects lower down in the graph because they’re owned by their parents,and you should minimize the risk of creating strong reference cycles.
From a practical perspective,in iOS and OS X outlets should be defined as declared properties. Outlets should generally be weak,except for those from File’s Owner to top-level objects in a nib file (or,in iOS,a storyboard scene) which should be strong. Outlets that you create should therefore typically be weak