Objective-c - Replace #import with #define

562 Views Asked by At

Is there a way to replace a class name #import through a #define macro? I want it to be made in all my project and not just in one file. So I don't want to make a #ifdef / #ifndef in each class that include the #import that I want to replace.

Something like... I have

#import "ClassSomething.h" 

in 5 classes. I want to replace it with an

#import "ClassSomethingCustom.h" 

but only

#ifdef SomethingIsDefined
4

There are 4 best solutions below

0
On BEST ANSWER

First, Objective-C's compiler (gcc or clang) do a good job of not cluttering the compiled source with duplicated header information. There's nothing wrong with including both headers - unless the headers re-define the same class (which is what I suspect is the case here).

Replace #import "ClassSomething.h" in all your files with #import CLASS_SOMETHING_HEADER

Then, in your .pch file, have the following:

#ifdef SomethingIsDefined
    #define CLASS_SOMETHING_HEADER "ClassSomethingCustom.h" 
#else
    #define CLASS_SOMETHING_HEADER "ClassSomething.h"
#endif

This isn't really ideal, though, as pre-processor macros that deal with imports can lead to many unforeseen errors. It's not a common pattern and future developers may not properly understand what you've done.

Another option you might want to consider is a pattern that is commonly used in libraries that support both iOS and OS X.

#ifdef SOME_IOS_IDENTIFIER_I_FORGOT_TO_LOOK_UP
    typedef UIColor MyColor
#else
    typedef NSColor MyColor
#endif

In this case you'd name your two classes differently and use an alias to reference them in your source. Place the relevant imports in a "parent" header file like "MyProjectImports.h" or something. (where you'd import AppKit or UIKit)

Alternatively, you might want to consider using a Category on ClassSomething (i.e. "ClassSomething+Custom.h") to include the custom functionality you need. This will likely require some re-working of the logic underlying the two different classes, but in the files that need just the custom behavior, can conditionally #import the Category header and the other files can be left alone.

Without more knowledge on exactly how these two classes differ or will be used, I can't help you much further.

HtH

1
On

Put this into a header file:

#ifdef SomethingIsDefined
#import "ClassSomethingCustom.h" 
#else
#import "ClassSomething.h"
#endif

and include this header file in you 5 classes.

2
On

You can change the content ClassSomething.h and put the #ifdef SomethingIsDefined only in there.

3
On

Perhaps what you need is to paste the code @dasdom wrote into your .pch file (pre-compiled header) file instead of every header. With that, you only need to paste it once and all the files will add this header automatically

#ifdef SomethingIsDefined
#import "ClassSomethingCustom.h" 
#else
#import "ClassSomething.h"
#endif

I hope this helps you. Otherwise, please can you explain it deeply?