如何有条件地遵守委托协议?

How to conditionally conform to delegate protocol?

如果我在我的 iOS 项目中包含仅在(例如)iOS 9 中可用的框架,但我仍然支持 iOS 8,我如何有条件地使用根据 iOS 版本是否符合委托协议?例如,我知道我可以像这样有条件地包含框架:

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

但是,如果该框架还需要遵守委托协议怎么办?

@interface ExampleController () <UITextViewDelegate, SomethingDelegate>

如果我在 iOS 9,如何只包含 "SomethingDelegate"?

谢谢!

嗯,大致相同的方式:

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

顺便说一句,这 不是 您应该检查设备是否 运行 iOS 9 - this only checks if your Xcode supports iOS 9 的方式。

@Glorfindel 的答案更干净,我会支持它,但只是为了有一个替代答案。

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

@interface ExampleController : UIViewController <DELEGATES>

还有一个问题,你打算如何处理属于 SomethingDelegate 协议的方法,还有 #ifdef/#endif 或者只是保留它们 "as is",因为它们永远不会被调用.

对于一个类别来说这是一个很好的任务,它有自己的文件。这些文件的内容完全可以 ifdefd 出来。

//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

这比将声明拆分成多行中间有一个宏好得多,并且将所有相关方法放在一个地方,在一个 ifdef.