user4034838
user4034838

Reputation: 121

How to conditionally conform to delegate protocol?

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!

Upvotes: 1

Views: 1081

Answers (3)

jscs
jscs

Reputation: 64002

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.

Upvotes: 1

teamnorge
teamnorge

Reputation: 794

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.

Upvotes: 1

Glorfindel
Glorfindel

Reputation: 22651

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.

Upvotes: 2

Related Questions