我们真的需要一个安全的发布宏吗? [英] Do we really need a safe release macro?

查看:52
本文介绍了我们真的需要一个安全的发布宏吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎很多人都在使用诸如

Quite a lot of people seem to use a macro such as

#define SAFE_RELEASE(X)  [X release]; X = nil;

(包括我自己).

我一直在重新评估我使用它的原因,并想征求一些意见.

I've been reassessing why I am using it and wanted to canvas some opinion.

使用这个宏的目的(我认为)是,如果你在释放对象后意外使用它,那么你不会得到一个错误的访问异常,因为objective-c当对象为 nil 时愉快地忽略它.

The purpose (I think) for using this macro is so that if you were to accidentally use your object after releasing it then you won't get a bad access exception because objective-c will quite happily ignore it when the object is nil.

我觉得这有可能掩盖一些晦涩的错误.也许当您再次尝试使用 X 时,程序崩溃实际上更可取.这样您就可以在测试期间找到问题并改进代码.

It strikes me that this has the potential to mask some obscure bugs. Maybe it would actually be preferable for the program to crash when you try to use X again. That way during testing you can find the issue and improve the code.

这个宏是否鼓励懒惰的编程?

Does this macro encourage lazy programming?

想法?

推荐答案

我认为您讨论了问题中的所有优点和缺点,因此我没有太多要补充的内容.我个人不使用该构造.正如您所建议的,它 可用于掩盖人们无法正确理解内存管理的领域.我的偏好是修复错误而不是症状.

I think you discuss all the pros and cons in your question, so I don't have a huge amount to add. Personally I don't use the construct. As you suggest, it can be used to paper over areas where people don't understand the memory management correctly. My preference is to fix the bug and not the symptom.

然而,我不时看到的一种妥协是:

However, one compromise that I have seen from time to time is:

  • 让它在开发过程中崩溃
  • 在生产代码中执行var = nil;

这样,它可能对付费客户更可靠,并且在开发过程中仍会在早期崩溃.

That way it might be more reliable with paying customers and still crashes early during development.

我也不热衷于此,因为您对用户使用不同的代码,仅仅因为有缺陷的版本继续运行并不意味着它在做正确的事情.不是崩溃而是破坏您的数据库不是可取的行为...

I'm not keen on this either, as you're using different code to your users and just because the buggy version keeps running doesn't mean it's doing the right thing. Not crashing but corrupting your database is not desirable behaviour...

这篇关于我们真的需要一个安全的发布宏吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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