在objective-c中,当对象本身被指定为它实现的委托时,对象如何返回不同的代理对象

Avn*_*arr 5 delegates objective-c objective-c-runtime nsinvocation ios

我有一个实现各种协议的对象(比如10个不同的协议).

例如

@interface MyClass <UITableViewDelegate,UITableViewDataSource,UISearchDisplayDelegate,...>

@end

@implementation

/// a whole bunch of methods for the delegates
@end
Run Code Online (Sandbox Code Playgroud)

为了在这个类中"清理"东西 - 我创建了辅助类,它封装了与这些委托相关的逻辑.

所以现在新的重构类看起来像

// public interface which looks the same
@interface MyClass <UITableViewDelegate,UITableViewDataSource,UISearchDisplayDelegate,...>


@end

// private interface

@interface MyClass ()

// a bunch of objects which implement those methods
@property (nonatomic,strong) MyUITableviewDelegate *tableViewDelegate;
@property (nonatomic,strong) MyUITableviewDataSource *tableViewDelegate;
@property (nonatomic,strong) MySearchDisplayDelegate *searchDisplayDelegate;
// another bunch of objects which answer to the delegates
@end

@implementation
// all the delegate methods were moved out of here to the class which implements the method

@end
Run Code Online (Sandbox Code Playgroud)

现在,当" MyClass" 的对象被指定为委托时 - 它应该返回"回答"那些委托的运行时对象(例如,如果" MyClass"对象被指定为UITableViewDelegate- MyUITableviewDelegate应该被分配.

如何才能做到这一点?我必须覆盖forwardInvocation" MyClass"对象吗?

Bry*_*hen 9

你需要实施 forwardingTargetForSelector:

- (id)forwardingTargetForSelector:(SEL)aSelector {
    if ([self.tableViewDelegate respondsToSelector:aSelector]) {
        return self.tableViewDelegate;
    }
    // etc

    return [super forwardingTargetForSelector:aSelector];
}
Run Code Online (Sandbox Code Playgroud)