Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do we really need a safe release macro?

Tags:

objective-c

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

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

(myself included).

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

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.

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?

Thoughts?

like image 925
Ian1971 Avatar asked Feb 21 '11 16:02

Ian1971


1 Answers

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:

  • Make it crash during development
  • Do the var = nil; in production code

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...

like image 169
Stephen Darlington Avatar answered Nov 14 '22 23:11

Stephen Darlington