使用属性在代码中创建UI

时间:2013-05-09 09:57:18

标签: ios cocoa-touch properties

当我通过Interface Builder创建UI然后附加到IBOutlets时,我总是将属性设置为弱...

@property (nonatomic, weak) IBOutlet UILabel *someLabel;

然后在UIViewController的代码中,我可以参考self.someLabel_someLabel,它可以正常使用。

但是,如果我在代码中设置UI ...

@property (nonatomic, weak) UILabel *someLabel;

和...

self.someLabel = [[UILabel alloc] initWithFrame:CGRectMake(0,0,10,10)];

然后我收到警告......

Assigning retained object to weak property; object will be released after assignment.

我通常的解决方法是将属性更改为strong,但我不确定这是否正确?

可以吗?如果没有,还有其他方法可以解决这个问题吗?

1 个答案:

答案 0 :(得分:2)

  

我通常的解决方法是将属性更改为强,但我不确定这是否正确?

这是100%正确。声明基于IB的属性weak的原因是,从NIB对象创建的视图已经保留了相应的UI元素,因此您不需要代码中的strong引用。