释放后将对象设置为 nil -- TT_RELEASE_SAFELY
我已经开始学习 Three20,我有一个关于 TT_RELEASE_SAFELY
的简单问题 到目前为止,我喜欢这样编写代码:
UILabel *lab = [[UILabel alloc] initWithFrame:rect];
[self.view addSubview:lab];
[lab release];
这里我认为主池负责释放lab
的内存。
现在我发现 TT_RELEASE_SAFELY
的定义如下:
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
如您所见,释放后,它将对象设置为 nil
。
我想知道这两种方式的区别以及哪种方式更好。
谢谢。
I have started to study Three20 and I have a simple question about TT_RELEASE_SAFELY
Up till now I like to write code in this way:
UILabel *lab = [[UILabel alloc] initWithFrame:rect];
[self.view addSubview:lab];
[lab release];
Here I think the main pool is responsible to free the memory of lab
.
Now I have found TT_RELEASE_SAFELY
which is defined like so:
#define TT_RELEASE_SAFELY(__POINTER) { [__POINTER release]; __POINTER = nil; }
As you can see, after release, it sets the object to nil
.
I'd like to know the difference between the two ways and which way is better.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
向 nil 发送消息 在 Objective-C 中是有效的。向已释放的对象发送消息则不然。
向已释放的对象发送消息:
向 nil 发送消息:
在对象被释放后将 nil 分配给变量是有争议的,因为它会阻止您意识到出现问题。 Sedate Alien 的示例:
由于 controlCenter 已被释放,此代码将崩溃。因此,该缺陷将被及早发现并修复。
此代码将向 timeLeft 分配 0.0,即使 controlCenter 为零,这似乎也是有效的等待时间。
对上述内容持保留态度,因为如果您正在编写 Objective-C 应用程序,您可能更关心通过避免崩溃来让用户满意,而不是破坏城市。如果后者是一个问题,您可能应该使用类型安全的语言,例如 Ada。
Sending a message to nil is valid in Objective-C. Sending a message to a deallocated object is not.
Sending a message to a deallocated object:
Sending a message to nil:
Assigning nil to a variable after an object has been deallocated is controversial because it can prevent you from realizing that something is wrong. Sedate Alien's example:
This code will crash since controlCenter has been deallocated. As a result this defect will be detected and fixed early.
This code will assign 0.0 to timeLeft which appears to be a valid wait time even though controlCenter is nil.
Take the above with a grain of salt, since if you are writing an Objective-C app, you are probably more concerned with keeping your users happy by avoiding crashes than destroying cities. If the latter is a concern, you should probably be using a type-safe language like Ada.
我相信使用这些“安全发布”的变体显然是一个坏主意。
您的应用程序将以无声且神秘的方式失败,因为传递给 nil 的消息不会引发任何警告。最好不要将引用清空,并充分利用 NSZombieEnabled 提供的所有功能。
I believe that using these variants of "safe releases" is an expressly bad idea.
Your application will fail in silent and mysterious ways, as messages passed to
nil
will not raise any warnings. It's much better to not nil out your references and take advantage of all thatNSZombieEnabled
has to offer.唯一的区别是 TT_RELEASE_SAFELY 在释放后将指针设置为 nil,因此释放后将不会使用该引用。该模式是一个很好遵循的模式,并且 TT_RELEASE_SAFELY 宏使其更易于实现。
The only difference is that TT_RELEASE_SAFELY sets the pointer to nil after release, so the reference won't be used after release. The pattern is a good one to follow and the TT_RELEASE_SAFELY macro makes it simpler to implement.