Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NS_BLOCK_ASSERTIONS in Objective-C

I am using NSAssert() calls within an iPhone application and my understanding from the Apple docs is that assertions are not compiled into the code if NS_BLOCK_ASSERTIONS is defined.

To turn off assertions, in a header file I declare: #define NS_BLOCK_ASSERTIONS

However, the assert code still seems to run.

Is there something I am missing here?

Thanks

John

like image 852
John Muchow Avatar asked Jun 22 '11 19:06

John Muchow


2 Answers

If you created your Xcode project based on one of the standard templates, the Cocoa headers (including NSException.h which contains the NSAssert macros) will get preprocessed before any other files in the project. A #define NS_BLOCK_ASSERTIONS in any of the project's header or implementation files therefore has no effect on the NSAssert macros.

Try putting NS_BLOCK_ASSERTIONS into the preprocessor macros of your target or even project (for the release configuration only):

GCC_PREPROCESSOR_DEFINITIONS = NS_BLOCK_ASSERTIONS

Or put #define NS_BLOCK_ASSERTIONS into the prefix (.pch) header before the #import <Cocoa/Cocoa.h> or #import <Foundation/Foundation.h> lines.

like image 100
puzzle Avatar answered Sep 20 '22 20:09

puzzle


As @dwsolberg mentioned, Xcode has a new build setting called ENABLE_NS_ASSERTIONS. For new projects its value for the release configuration is set to NO and for all other configurations to YES. You can use this setting as well as the widely used NS_BLOCK_ASSERTIONS approach which is still valid in Xcode 6.

Preprocessor Macro Approach

Foundation Assertion Build Setting

Assertions are a tool to track down bugs during development time and should never fire in productive code! Also exceptions should be used only if it is absoloutely neccessary, i.e. if something went so damn wrong that the programm is not able to continue execution. The Cocoa way is to give critical methods a boolean return value and parametrize them with an error object that can be set inside the method and can be used outside if the return value is NO.

Hope that helps some folks ;-)

like image 24
blackjacx Avatar answered Sep 20 '22 20:09

blackjacx