Search code examples
iosobjective-cc-preprocessorpreprocessor-directive

Use compiler conditional to control delegate implementation?


Is it possible to use a compiler directive to control if a particular delegate is implemented?

For example, in the following code, I only want to include a library if we're a constant is defined:

#ifdef kShouldLoadFromCSV
#import "CHCSVParser.h"
#endif

@interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate, CHCSVParserDelegate>{

If kShouldLoadFromCSV is undefined, I don't want to implement CHCSVParserDelegate. I've tried sticking the compile directive in the interface declaration, but that didn't work.

Is there a way to do this?


Solution

  • You could do this:

    #if kShouldLoadFromCSV
        @interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate, CHCSVParserDelegate>{
    #else
        @interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate>{
    #endif
    

    Or if you wish, maybe harder to read, a matter of taste:

        @interface MyAppDelegate : NSObject <UIApplicationDelegate, UITabBarControllerDelegate
    #if kShouldLoadFromCSV
          , CHCSVParserDelegate
    #endif
    >{
    

    You have to remember that the preprocessor isn't syntax aware, it will just affect the input of the compiler.