惯用寿命短的局部物体,类似于RAII [英] Idiomatic short lifespan local objects akin to RAII
问题描述
我遇到了Objective-C的这个片段:
I came across this fragment of Objective-C:
NSNumber *theBalance =
[[[NSNumberFormatter alloc] init]
numberFromString: [textField text]];
这似乎泄漏了NSNumberFormatter
.在C ++中,我将执行以下两项操作之一:
This seems to leak the NSNumberFormatter
. In C++ I would do one of two things:
- 将
auto
(即堆栈)存储用于NSNumberFormatter
- 使用RAII(例如
shared_ptr
)来管理NSNumberFormatter
的寿命
- use
auto
(i.e. stack) storage for theNSNumberFormatter
- use RAII (e.g.
shared_ptr
) to manage the life of theNSNumberFormatter
在Objective-C中,这些选项似乎都不可行.我在堆栈上尝试过:
In Objective-C neither of these options seem to be possible. I tried on the stack:
NSNumberFormatter fmt;
但这无法编译.据我所知,在Objective-C中没有RAII的直接等效项.作为主要的C ++程序员,我可能是从错误的角度看问题,所以:
But this doesn't compile. As far as I can find there's no direct equivalent of RAII in Objective-C. I'm probably looking at the problem from the wrong angle as a mainly C++ programmer, so:
- 在一般情况下,什么是正确的,惯用的(现代的)Objective-C方法来处理诸如
NSNumberFormatter
这样的对象的寿命?我真的必须自己明确地做吗? - 在特定情况下,有没有更好的方法来解决实际问题?
- In the general case what's the correct, idiomatic (modern) Objective-C way of handling the life of objects like the
NSNumberFormatter
here? Do I really have to do it explicitly myself? - In the specific case is there a better way of solving the actual problem?
推荐答案
大多数类,例如 NSString , NSArray 等,具有便捷的构造函数,例如[NSString string]
和[NSArray array]
会返回自动释放的对象. NSNumberFormatter 没有任何方便的构造函数.因此,您可以发送autorelease
消息,以在自动释放池耗尽时自动释放它.
Most of the classes like NSString, NSArray, and so on, have the convenience constructors like, [NSString string]
and [NSArray array]
which return the autoreleased objects. NSNumberFormatter doesn't have any convenience constructors. So, you can send a autorelease
message to let it autoreleased when the autorelease pool drains.
NSNumber *theBalance = [[[[NSNumberFormatter alloc] init] autorelease]
numberFromString: [textField text]];
如果要保留(拥有)对象的引用,可以省略autorelease
并在完成后释放它.你是这样做的,
If you want to retain(own) the reference of the object, you can omit the autorelease
and release it later when you are done with it. You do it like this,
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *theBalance = [numberFormatter numberFromString: [textField text]];
// Later... somewhere in your code...
[numberFormatter release];
我知道上面没有详细解释.我建议您阅读这篇文章希望您能对内存管理有个清晰的认识!
I know the above is not a detailed explanation. I'd suggest you to read this post by which, I hope, you would get some clear idea about memory management!
这篇关于惯用寿命短的局部物体,类似于RAII的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!