简体   繁体   中英

How can I use different .h files for several targets?

I have a project with several targets. For most of my classes, I can use a single .h file and change the details in the .m file (adding a different .m file for each target).

For one of my UIViewController subclasses, I need to declare different UILabel IBOutlet s for the different targets (each target shows a different set of labels depending on what's available). The problem is that header files can't be targeted. There's no checkbox next to them to specify target membership.

The way I've been dealing with this is to just add outlets for all of the targets and ignore the unused ones. It doesn't seem ideal.

Do I need to use a header build phase for this? What's the best way to deal with this problem? Thanks.

Edit: I should have mentioned that I want all the .h files to have the same name: PlaceViewController.h .

You can use preprocessor directives to selectively include the header files. For instance

#if TARGET_OS
   #import "FirstTarget.h"
#else
   #import "SecondTarget.h"
#endif

You can use different folders for different targets if the headers are the named the same:

#if TARGET_OS
   #import "First/Target.h"
#else
   #import "Second/Target.h"
#endif

You can read more about conditionals here .

Headers don't get compiled themselves, but are included in other files which are then compiled. You can use conditional compilation inside those files to include the correct headers for the target. Define a unique symbol in the preprocessor symbols for each target, and include the appropriate headers accordingly:

#if defined(TARGET_ONE)
#include "HeaderOne.h"
#elif defined(TARGET_TWO)
#include "HeaderTwo.h"
#endif

I'm sorry to be answering a couple of years too late, but I recently had the same problem, and there's a way to do this:

  • Let's say you already created a new target by duplicating the original target. Right-click the first (original) .h file in the Project Navigator and open the file in Finder.
  • In Xcode, right-click the file, and remove it from the project (only remove reference, do not move to trash).
  • In Finder, create two folders (you can't have two same-named files in a single folder), and move/copy the original .h file in both of them.
  • Now, drag-and-drop the first folder somewhere in your project, and when the window with the targets pops out, select only the first target.
  • Same with the second folder, select only the second target.

Voilà, you should now have two same-named .h files.

Caveats: it seems Xcode has random problems if your .h file has an NS_ENUM . It is probably solvable, but I still haven't figured it out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM