Why are macros in Objective-C / Cocoa?

I come from a place without macros (Java / Python / C # / Scala), so maybe my perspective is distorted, but ...

Why are macros used in Cocoa? Two of them: spring - NSLocalizedString and NSAssert (and STAssert ). Would it be so difficult / inappropriate for them to perform functions (which could be included)? I suppose I find them a little strange, like an unnecessary return to C (and yes, I am familiar with the obj-C pedigree).

Is it something that was done that day or is there a specific reason?

+4
source share
2 answers

In general, it is advisable to avoid macros, but for functions like the NSAssert() function, you cannot.

If you look at the definition, you will see that it uses __LINE__ , __FILE__ , _cmd and self from the context in which it is used. If it's not a macro, don't have access to this information.

However, for NSLocalizedString I see no obvious reason.

+8
source

NSLocalizedString is a handy macro and can probably be executed as a function.

However, there are good reasons why NSAssert and friends are macros other than those specified in George's answer. NSAssert evaluates the boolean expression to determine if an exception should be thrown. This logical expression can be quite expensive computational rather than what you want to do in your release code. There is no mechanism in C (and therefore Objective-C) that omits the usual function calls to build the release without resorting to a preprocessor or, possibly, using things such as:

 if (debug) { assertAsAFunction(foo == 3, "foo should be 3"); } 

Another advantage of the NSAssert macro is that the condition can be compressed for use in a log message.

+4
source

Source: https://habr.com/ru/post/1310247/


All Articles