惯用寿命短的局部物体,类似于RAII [英] Idiomatic short lifespan local objects akin to RAII

查看:108
本文介绍了惯用寿命短的局部物体,类似于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:

  1. auto(即堆栈)存储用于NSNumberFormatter
  2. 使用RAII(例如shared_ptr)来管理NSNumberFormatter的寿命
  1. use auto (i.e. stack) storage for the NSNumberFormatter
  2. use RAII (e.g. shared_ptr) to manage the life of the NSNumberFormatter

在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:

  1. 在一般情况下,什么是正确的,惯用的(现代的)Objective-C方法来处理诸如NSNumberFormatter这样的对象的寿命?我真的必须自己明确地做吗?
  2. 在特定情况下,有没有更好的方法来解决实际问题?
  1. 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?
  2. 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屋!

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