具有ios界面元素的强弱修饰符

在我的项目中,我不使用Interface Builder,我注意到一件我不知道如何解释的事情.然而.所以,到了这一点.当我们在控制器中使用IB并定义用户界面的元素(如UILabel或UIButton)时,我们使用这个丑陋的前缀IBOutlet和一个“弱”修饰符.这就像音乐一样.但是当我们决定不使用IB并从代码中定义整个用户界面时,它就不起作用了.

假设我想将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];

直到我将* .h文件更改为此内容才能生效:

@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

以上是来客网为你收集整理的具有ios界面元素的强弱修饰符全部内容,希望文章能够帮你解决具有ios界面元素的强弱修饰符所遇到的程序开发问题。

如果觉得来客网网站内容还不错,欢迎将来客网网站推荐给程序员好友。