解除分配 IBOutlet 和实例变量
这是我很久以前就应该解决的问题,但我只需要知道在以下场景中解除分配的最佳实践。
在我的头文件中,我声明了对 IBOutlet 的引用,如下所示:
@interface Test : UIViewController {
UIButton *_loginBtn;
}
@property (nonatomic, retain) IBOutlet UIButton *loginBtn;
在实现文件中,我将实例变量关联到属性并按如下方式解除分配:
@implementation Test
@synthesize loginBtn = _loginBtn;
...
- (void) dealloc {
[_loginBtn release];
self.loginBtn = nil;
[super dealloc];
}
- (void) viewDidUnLoad {
[_loginBtn release];
self.loginBtn = nil;
[super viewDidUnLoad];
}
我在解除分配实例变量和设置方面是否正确属性为 nil
并在 viewDidUnLoad
和 dealloc
方法中执行此操作?
This is something I should have cleared up long ago, but I just need to know the best practice for deallocating in the following scenario.
In my header file I declare a reference to an IBOutlet
as follows:
@interface Test : UIViewController {
UIButton *_loginBtn;
}
@property (nonatomic, retain) IBOutlet UIButton *loginBtn;
And in the implementation file I associate the instance variable to the property and deallocate as follows:
@implementation Test
@synthesize loginBtn = _loginBtn;
...
- (void) dealloc {
[_loginBtn release];
self.loginBtn = nil;
[super dealloc];
}
- (void) viewDidUnLoad {
[_loginBtn release];
self.loginBtn = nil;
[super viewDidUnLoad];
}
Am I correct in the deallocating the instance variable and setting the property to nil
and doing this in both the viewDidUnLoad
and dealloc
methods?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
dealloc 中不需要 self.loginBtn = nil; ,上一行将其释放。最好不要在dealloc中使用该属性来释放它。释放 vs 将属性设置为 nil 的原因是 setter 是一个方法调用,并且该类正处于拆除过程中,事情可能不稳定。
在
viewDidUnLoad
中释放IBOutlet
的任何属性,其中self.theOutlet = nil;
,在本例中是_loginBtn 释放];< /code> 不是必需的并且是多余的。同时释放您可以轻松重新创建的任何其他对象。
如果使用属性,则应将它们用于类中的所有访问,但有两个例外:init 和 dealloc。在这两种情况下,课程都是部分完成的。在这两种情况下,最好直接在
init
中使用 ivar(如果需要),并在dealloc
中使用release
。There is no need for
self.loginBtn = nil;
indealloc
, the previous line released it. It is best not to use the property to release it in dealloc. The reason for releasing vs setting the property to nil is that the setter is a method call and the class is in the midst of tearing down and things may be unstable.In
viewDidUnLoad
release any properties that areIBOutlet
s withself.theOutlet = nil;
, in this case the_loginBtn release];
is not needed and redundant. Also release any other objects that you can easily re-create.If properties are used they should be used for all accesses in the class with two exceptions: init and dealloc. In both of these cases the class is partially complete. In these two cases it is best to use the ivar directly in
init
(if necessary) andrelease
indealloc
.不,这是不正确的。通过首先释放 _loginBtn 然后将该属性设置为 nil,可以释放该实例两次。正确的做法是释放 _loginBtn 然后将 _loginBtn 设置为 nil。
No, this is incorrect. By first releasing _loginBtn and then setting the property to nil, you release the instance twice. The correct way to do it is to release _loginBtn and then set _loginBtn to nil.