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?
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.
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.
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.
You need to implement forwardingTargetForSelector:
- (id)forwardingTargetForSelector:(SEL)aSelector {
if ([self.tableViewDelegate respondsToSelector:aSelector]) {
return self.tableViewDelegate;
}
// etc
return [super forwardingTargetForSelector:aSelector];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With