我有一個視圖控制器,它定義了一個協議本身繼承另一個協議。 我想要任何實現我的協議的對象也實現繼承的協議。目標C與forwardingTargetForSelector轉發並不總是工作的消息
我想設置我的課攔截一些在繼承協議的消息以內部配置一些東西,但最終還是希望所有的郵件轉發到我班的代表
我可以寫許多鍋爐板代碼來存留所有的協議和實習生致電委託,但我看到它打破了很多時間 - 任何時候「超級」協議的變化我需要再次重新設置這個類。
我看到這在自定義用戶界面控件中非常佔優勢。在重用現有組件(例如表或集合視圖)時,您希望數據源響應所有常用協議,但有些實例需要根據索引配置視圖或保存特定狀態。
我以轉發我不迴應消息使用forwardingTargetForSelector
試過,但它並不總是轉發...
這裏是一個人爲的代碼示例:
Class A: (the top most protocol)
@
protocol classAProtocol <NSObject>
-(void)method1;
-(void)method2;
-(void)method3;
@end
My Class
@protocol MyClassProtocol <classAProtocol>
-(void)method4;
@end
@interface MyClass
@property (nonatomic,weak> id <MyClassProtocol> delegate;
@end
@interface MyClass (privateInterface)
@property (nonatomic,strong) ClassA *classAObject;
@end
@implementation MyClass
-(init)
{
self = [super init];
if (self)
{
_classAObject = [[ClassA alloc] init];
_classAObject.delegate = self; // want to answer some of the delegate methods but not all
}
}
-(void)method1
{
// do some internal configuration
// call my delegate with
[self.delegate method1];
}
-(id)forwardingTargetForSelector:(SEL)aSelector
{
if ([self respondsToSelector:aSelector])
{
return self;
}
if ([self.delegate respondsToSelector:aSelector])
{
return self.delegate;
}
return nil;
}
-(void)setDelegate:(id <MyClassProtocol>)delegate
{
self.delegate = delegate; // will forward some of the messages
}
@end
將嘗試您的解決方案,並送還給你。 –