1

If I am including frameworks in my iOS project that are only available in (for example) iOS 9, but I am still supporting iOS 8, how do I conditionally conform to a delegate protocol depending on the iOS version? For example, I understand I can include the framework conditionally like this:

#import <Availability.h>
#ifdef __IPHONE_9_0
#import <Something/Something.h>
#endif

But what if that framework also needs to conform to a delegate protocol?

@interface ExampleController () <UITextViewDelegate, SomethingDelegate>

How do I only include "SomethingDelegate" if I'm on iOS 9?

Thanks!

user4034838
  • 121
  • 9

3 Answers3

2

Well, in roughly the same manner:

@interface ExampleController () <UITextViewDelegate
#ifdef __IPHONE_9_0
     , SomethingDelegate
#endif
>

By the way, this is not the way you should check if the device is running iOS 9 - this only checks if your Xcode supports iOS 9.

Community
  • 1
  • 1
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
1

The answer of @Glorfindel is more clean, and I would support it, but just to have an alternative answer.

#ifdef __IPHONE_9_0
    #import <Something/Something.h>
    #define DELEGATES UITextViewDelegate, SomethingDelegate
#else
    #define DELEGATES UITextViewDelegate
#endif

@interface ExampleController : UIViewController <DELEGATES>

And there is also a question, what are you going to do with methods belonging to SomethingDelegate protocol, also #ifdef/#endif or just keep them "as is", as they never be called.

teamnorge
  • 784
  • 5
  • 9
1

This is a good task for a category, with its own files. The contents of those files can be entirely ifdefd out.

//ExampleController+SomethingDelegate.h
#ifdef __IPHONE_9_0

#import <Something/Something.h>

@interface ExampleController (SomethingDelegate) <SomethingDelegate>
@end
#endif

//ExampleController+SomethingDelegate.m
#import "ExampleController+SomethingDelegate.h"

#ifdef __IPHONE_9_0

@implementation ExampleController (SomethingDelegate) <SomethingDelegate>

 - (BOOL)somethingShouldMakePancakes:(Something *)something;    

@end

#endif

This reads much better than splitting the declaration across multiple lines with a macro in the middle, and keeps all the relevant methods in one place, under one ifdef.

jscs
  • 63,694
  • 13
  • 151
  • 195