In objective-c , how can an object return a different proxy object when itself is assigned as a delegate it implements
Asked Answered
K

1

5

I have an object which implements various protocols (like 10 different ones).

For example

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

@end

@implementation

/// a whole bunch of methods for the delegates
@end

In order to "clean" things up in this class - I have created helper classes which encapsulates the logic pertaining to those delegates.

so now the new refactored class looks something like

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

Now when an object of "MyClass" is assigned as a delegate - it should return the runtime object which "answers" to those delegates (for instance if "MyClass" object is assigned as a UITableViewDelegate - the MyUITableviewDelegate should be assigned.

How can this be done? Must I override the forwardInvocation in the "MyClass" object?

Katz answered 30/7, 2014 at 5:40 Comment(0)
I
9

You need to implement forwardingTargetForSelector:

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

    return [super forwardingTargetForSelector:aSelector];
}
Istanbul answered 30/7, 2014 at 6:1 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.