惯用的短寿命本地对象类似于 RAII
我遇到了 Objective-C 的这个片段:
NSNumber *theBalance =
[[[NSNumberFormatter alloc] init]
numberFromString: [textField text]];
这似乎泄漏了 NSNumberFormatter
。在 C++ 中,我会做以下两件事之一:
- 使用
auto
(即堆栈)存储NSNumberFormatter
- 使用 RAII(例如
shared_ptr
)来管理NSNumberFormatter
的生命周期
在 Objective-C 中,这两个选项似乎都不可能。我在堆栈上尝试过:
NSNumberFormatter fmt;
但这无法编译。据我所知,Objective-C 中没有直接相当于 RAII 的东西。作为一个主要是 C++ 的程序员,我可能从错误的角度看待这个问题,所以:
- 在一般情况下,处理像 NSNumberFormatter 这样的对象的生命周期的正确的、惯用的(现代的)Objective-C 方式是什么?代码>这里?我真的必须自己明确地做吗?
- 在具体案例中是否有更好的方法来解决实际问题?
I came across this fragment of Objective-C:
NSNumber *theBalance =
[[[NSNumberFormatter alloc] init]
numberFromString: [textField text]];
This seems to leak the NSNumberFormatter
. In C++ I would do one of two things:
- use
auto
(i.e. stack) storage for theNSNumberFormatter
- use RAII (e.g.
shared_ptr
) to manage the life of theNSNumberFormatter
In Objective-C neither of these options seem to be possible. I tried on the stack:
NSNumberFormatter fmt;
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:
- 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
大多数类(例如 NSString、NSArray 等)都具有方便的构造函数,例如
[NSString string]
和[NSArray array]
返回自动释放的对象。 NSNumberFormatter 没有任何便利的构造函数。因此,您可以发送一条autorelease
消息,让它在自动释放池耗尽时自动释放。如果您想保留(拥有)对象的引用,您可以省略
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 aautorelease
message to let it autoreleased when the autorelease pool drains.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,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!