Search code examples
objective-cmethodsinline

Can I inline static class methods in Objective-C?


You can declare functions as inlines like this:

#ifdef DEBUG
void DPrintf(NSString *fmt,...);
#else
inline void DPrintf(NSString *fmt,...) {}
#endif

so that when you're not in DEBUG, there's no cost to the function because it's optimized and inline. What if you want to have the same thing but for a class method?

My class is declared like this:

@interface MyClass : NSObject {

}

    + (void)DPrintf:(NSString *)format, ...;
    // Other methods of this class
@end

I want to convert 'DPrintf' into something similar to the inline so that there's no cost to invoking the method.

But I can't do this:

inline +(void)DPrintf:(NSString *)format, ...; {}

How can I have a zero-cost static method of a class turned off for non-debug compilations?


Solution

  • Be careful. Objective-C methods are not the same as C functions. An Objective-C method is translated by the compiler into the objc_msgSend() function call; you don't have control over whether a method is inline or not because that is irrelevant. You can read more about the Objective-C runtime here (Objective-C Runtime Programming Guide), here (Objective-C Runtime Reference), and here (CocoaSamurai post), and a quick Google search should bring up more info.