Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I conditionally declare a delegate in an interface declaration?

I have an Xcode 4 project that builds to two different targets. I've defined some constants in the build settings so I can run different code for each target like this:

#ifdef VERSION1
// do this
#else
// do that
#endif

In one version of the app, I need the main view controller to open another view controller and become its delegate, but the other version doesn't use that view controller and shouldn't compile its code or try to become its delegate. I've set up the main view controller header like this:

#ifdef VERSION2
#import "SpecialViewController.h"
#endif

@interface MainViewController : UIViewController <MPMediaPickerControllerDelegate, SpecialViewControllerDelegate> {
// etc.

The conditional around the #import tag works fine, but how can I declare this class to be the SpecialViewControllerDelegate in one version but not the other?

like image 636
arlomedia Avatar asked Jul 01 '11 17:07

arlomedia


2 Answers

Just use a #define preprocessor directive to change the delegates between versions. Here's an example for "VERSION2".

#ifdef VERSION2
#import "SpecialViewController.h"
#define ARGS PMediaPickerControllerDelegate, SpecialViewControllerDelegate 
#endif

@interface MainViewController : UIViewController <ARGS>
like image 108
Zéychin Avatar answered Nov 08 '22 06:11

Zéychin


As long as you don't assign the delegate you should be fine leaving the implementation. Your SpecialViewController in VERSION1 (if you even have a SpecialViewController in V1) will not have a delegate so its calls will go nowhere, which should lead to no side effects.

#ifdef VERSION2
specialViewController.delegate = self;
#endif

If this approach doesn't work it almost seems like you should have a different MainViewController for each target.

like image 32
Chris Wagner Avatar answered Nov 08 '22 08:11

Chris Wagner