Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 784
Avner Barr Avatar asked Jul 30 '14 05:07

Avner Barr


People also ask

How do delegates work in Objective-C?

A delegate is an object that acts on behalf of, or in coordination with, another object when that object encounters an event in a program. The delegating object is often a responder object—that is, an object inheriting from NSResponder in AppKit or UIResponder in UIKit—that is responding to a user event.

How do you declare a protocol in Objective-C?

In Objective-C, you add the protocol name in angle brackets beside the class interface declaration. MyClass is declaring that it conforms to SampleProtocol below. MyClass will also have to provide an implementation for “someMethod” in the implementation file because it is a required protocol method.

What is ID in Obj C?

id is the generic object pointer, an Objective-C type representing "any object". An instance of any Objective-C class can be stored in an id variable.


1 Answers

You need to implement forwardingTargetForSelector:

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

    return [super forwardingTargetForSelector:aSelector];
}
like image 132
Bryan Chen Avatar answered Sep 17 '22 21:09

Bryan Chen