使用 iPhone SDK 保留 NIB/XIB 内的控件与分配控件
我正在使用 Interface Builder 来构建我的 rootViewController,它由我的应用程序委托保留。我在这个 XIB 中有一些控件,例如几个 UIButtons、一个 UISlider 等,作为 IBOutlet,在 Interface Builder 中正确连接。
在XIB的代码实现方面,我看到有人使用:
@interface RootViewController : UIViewController {
IBOutlet UIButton *button1;
IBOutlet UIButton *button2;
...
}
@property(nonatomic, assign) UIButton *button1;
@property(nonatomic, assign) UIButton *button2;
@end
为什么他们使用分配而不是保留?我见过有些人甚至不使用分配属性。
使用保留是没有意义的,因为 rootViewController 的 XIB 只要加载就始终包含对它们的引用?或者他们只是懒惰,没有完成保留、综合和总结的步骤。解除分配?在我看来,只要需要控制并且 viewController 没有被释放,保留引用就不会造成什么坏处,但只是想知道 XIB 是否会在不需要的地方做一些不同的事情。
顺便说一句,我已经阅读了内存管理指南。
谢谢!
I'm using Interface Builder to build my rootViewController, which is retained by my application delegate. I have a few controls in this XIB such as a couple UIButtons, a UISlider, etc. as IBOutlets, hooked up properly in Interface Builder.
On the code implementation side of the XIB, I've seen some people use:
@interface RootViewController : UIViewController {
IBOutlet UIButton *button1;
IBOutlet UIButton *button2;
...
}
@property(nonatomic, assign) UIButton *button1;
@property(nonatomic, assign) UIButton *button2;
@end
Why do they use assign instead of retain? I've seen some people not even use an assign property.
Is it pointless to use retain since the rootViewController's XIB will always contain a reference to them as long as it is loaded? Or are they just being lazy and not going through the steps to retain, synthesize & dealloc? Seems to me like it can't hurt to keep a reference around as long as the control is needed and the viewController hasn't been dealloc'ed, but just wondering if XIB's do something differently where this wouldn't be necessary.
I've read the memory management guide, btw.
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只要子视图仍然是超级视图的子视图,将所有子视图保留为分配状态而不是保留状态并没有什么坏处。
当您从其超级视图中删除它并希望稍后将其添加为代码中的子视图时。那是不可能的。当您将其从超级中删除时,其保留计数可能会变为零。这就是您使用保留的原因之一。然后,您的控制器对象将始终是视图对象的所有者。
我想不出您必须使用保留而不是分配的其他原因。
我总是使用保留,我认为这是插座的最佳实践,而且它似乎是一种约定。
It cant hurt to keep all subviews as assigned instead of retained as long as they stay a child from there superview.
When you remove it from its superview and want to add it as a subview later on in your code. Thats not possible. When you remove it from its super its retain count will probably turn to zero. Thats one of the reasons why you use retain. Your controller object will then always be a owner of the view object.
I cant think of other reasons you must use retain instead of assign.
I always use retain, i think its a best practice for outlets and it seems to be a convention.