I've got an Xcode project with three different targets (say soccer, baseball, basketball) resulting in three different apps. Most of the code is the same, but sometimes it's target-specific.

What's the best way to implement methods which are specific to a target? I'd like to avoid

if ([AppDelegate isSoccerTarget] {
   ...
} else if () {
   ...
} else if () {
   ...
}

I was thinking about using categories which only exist in one of the three targets, but then I can't use a default implementation. And I'd like to avoid inheritance as some classes are already in a class hierarchy and I'd like to keep that simple (avoid person => player, manager resulting in soccerPlayer, basketballPlayer etc.).

What's your way of doing this?

有帮助吗?

解决方案

The way I handle it is I place anything that is similar in a super class that is added to all targets, and then I create a new class (for your example "Player") that is different for each target.

So in the source directory I would have subdirectories and files:

basketball/Player.m baseball/Player.m ...

And then I would select the "Target Membership" for basketball/Player.m to be the "Basketball" target.

This way I only have to instantiate a Player class once and depending on what my target is, it will automatically create the proper class. Hope this helps.

其他提示

You would make your targets in the Xcode project pane (the file at the very top), and then, in one of the tabs in each target (I forget which one) add some values in the preprocessor macros (might be pre compiler macros). Then, in your code, you can do this: say your preprocessor macro for the baseball target was called BASEBALL and soccer was SOCCER. Your code would look like this:

...blablablaothercode...
#ifdef BASEBALL
      NSLog(@"Baseball!");
#endif
#ifdef SOCCER
      NSLog(@"Soccer!");
#endif
...blablablaothercode...

These can be used anywhere normal code could be used. Think of it as a 'switch' statement that the compiler can use to see what code to use for each target.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top