代理的内存管理? [英] Memory management with delegates?

查看:89
本文介绍了代理的内存管理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

代理的内存管理,我的理解是,我不保留代理,如果视图卸载(通过viewDidUnload)和以后重新创建(通过viewDidLoad),我有点不确定如何处理委托? / p>

Memory management with delegates, it is my understanding that I don't retain delegates, I am a little unsure about what to do with the delegate if the view gets unloaded (via viewDidUnload) and later recreated (via viewDidLoad)?

@property(assign) SomeClass *someDelegate;

- (void)viewDidLoad {
    [super viewDidLoad];
    someDelegate = [[SomeClass alloc] init];
    [someDelegate setDelegate:self];
}

-(void)viewDidUnload {
    [super viewDidUnload];
    [self setSomeDelegate:nil];
}

-(void)dealloc {
[super dealloc];
}



PS:我可能在错误的轨道,我只是想我的头围这... ...

PS: I might be on the wrong track, I am just trying to get my head round this ...

干杯Gary

推荐答案

你使用assign为你的属性,你不是调用保留对象上。

If you use assign for your property, you're not calling retain on the object.

这意味着你绝对不应该调用release或autorelease就可以了!

This means that you should definitely NOT call release or autorelease on it!

您的dealloc中的行

Your line in your dealloc

[someDelegate release];

会在未来某个时间点导致崩溃 - 您应该删除它。

will cause a crash at some point down in the future - you should remove it. You don't need to care about assigned properties in the dealloc method.

您的行

[self setSomeDelegate:nil];

不会泄漏。

但是,你的 viewDidLoad [[someDelegate alloc] init] >方法。这是不寻常的;它是正常的委托是一个外部对象,而不是自己做的。在你的情况下,它不是一个委托,它只是一个对象,为你做一些事情 - 你应该重命名它,并将属性更改为一个retain(并记得释放它在dealloc)。

However, you seem to have [[someDelegate alloc] init] in your viewDidLoad method. This is unusual; it's normal for the delegate to be an external object, not one made by yourself. In your case, it's not really a delegate, it's just an object that does something for you - you should rename it and change the property to a retain (and remember to release it in dealloc).

目前,如果你的属性设置为(assign)并且有人设置它,你将泄漏你的初始委托。如果你只使用这个类中的委托,也许它不应该是一个属性?如果你只是想从类外部读取它,你可以使用(readonly)而不是assign(并将 [self setSomeDelegate:nil] 更改为 someDelegate = nil;

Currently, if your property is set to (assign) and someone else sets it, you will leak your initial delegate. If you only use the delegate inside this class, perhaps it shouldn't be a property at all? If you just want to be able to read it from outside your class you might be able to use (readonly) instead of assign (and change [self setSomeDelegate:nil] to someDelegate=nil;)

您的行 viewDidUnload 将委托设置为nil删除您在第二个注释中引发的问题 - 您要删除委托,所以当您到达 viewDidLoad 时,您的委托已经是nil: )

Your line in viewDidUnload that sets the delegate to nil removes the issue you raise in your second comment - you're removing the delegate so by the time you get to viewDidLoad again, your delegate is already nil :)

这篇关于代理的内存管理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆