Objective-C自动释放存储器管理 [英] Objective-C autorelease memory management

查看:111
本文介绍了Objective-C自动释放存储器管理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在阅读 关于内存管理 当你有一个方法作为一个工厂方法 - 通过创建一个新的对象并返回它的方法没有办法释放对象,然后返回它,因为这将导致一个被释放的对象被返回。



示例

   - (Test *)createNewTest 
{
Test * newInstance = [[Test alloc] init];
[newInstance release];
return newInstance; // deallocted对象返回。
}

而是应该使用 autorelease


由NSObject定义的autorelease方法会将接收器标记为稍后发布




我的问题是:如果对象稍后被释放,我如何知道它何时被释放?

   - (Test *)createNewTest 
{
Test * newInstance = [[test alloc] init];
[newInstance autorelease];
return newInstance;
}

- (void)runIt
{
Test * myInstance = [self createNewTest];
// when is myInstance released?从而不再对我的功能有效?
}

如何安全地使用返回的自动释放对象在 runIt 方法如果我不知道什么时候autorelease发生?我应该保留 createNewTest 返回的对象吗?或者我可以安全地在 runIt 范围内使用它吗?

解决方案

自动释放对象已添加到自动释放池。



自动释放池中的对象在主runloop的迭代结束时释放(如果您正在管理自己的自动释放池和/或调用drain,则会更早)。



当你调用返回一个自动释放对象的方法时,它几乎可以保证有效,直到它被调用的范围的结束。



如果你想确保它活着的时间更长,那么你应该保留它,记住在完成它后再次释放它。


Im trying to understand when to call autorelease, and what this will actually do to my object.

After reading About Memory Management in the Mac Developer Library I understood that when you have a method that acts as a factory method - by creating a new object and returning it - the method has no way of releasing the object before returning it, because this would result in a deallocted object being returned.

Example

- (Test *) createNewTest 
{
    Test *newInstance = [[Test alloc] init];
    [newInstance release];
    return newInstance; // deallocted object returned.
}

Instead I should use autorelease:

The autorelease method, defined by NSObject, marks the receiver for later release

My question is: if the object is to be released later, how do I know when its being released?

- (Test *) createNewTest 
{
    Test *newInstance = [[test alloc] init];
    [newInstance autorelease];
    return newInstance;
}

- (void) runIt
{
    Test *myInstance = [self createNewTest];
    // when is myInstance released?? and thereby not valid to my function anymore?
}

How can I safely use the returned autoreleased object inside my runIt method if I don't know when the autorelease happens? Should I retain the object returned by the createNewTest? Or can I safely use it within the runIt scope?

解决方案

An autoreleased object is added to an autorelease pool.

Objects in the autorelease pool are released at the end of an iteration of the main runloop (or sooner if you are managing your own autorelease pool and/or if you call drain).

When you call a method that returns an autoreleased object, it is pretty much guaranteed to stay valid until at least the end of the scope that it was called in.

If you want to ensure that it stays alive longer then you should retain it, remembering to release it again when you're finished with it.

这篇关于Objective-C自动释放存储器管理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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