我遇到了 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 方式是什么?我真的必须自己明确地这样做吗? - 具体情况下有没有更好的方法来解决实际问题?
最佳答案
大多数类,如 NSString、NSArray 等,都有方便的构造函数,例如 [NSString string]
和 [NSArray array]
返回自动释放的对象。 NSNumberFormatter 没有任何便利的构造函数。因此,您可以发送一条 autorelease
消息,让它在自动释放池耗尽时自动释放。
NSNumber *theBalance = [[[[NSNumberFormatter alloc] init] autorelease]
numberFromString: [textField text]];
如果您想保留(拥有)对象的引用,您可以省略autorelease
并在使用完毕后释放它。你这样做,
NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
NSNumber *theBalance = [numberFormatter numberFromString: [textField text]];
// Later... somewhere in your code...
[numberFormatter release];
我知道上面并不是详细的解释。我建议你read this post我希望您能够通过本文对内存管理有一些清晰的了解!
关于iphone - 惯用的短生命周期本地对象类似于 RAII,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7753680/