Is it possible to dynamically implement a protocol in Objective-C?

I know that I can extend a class (for example, the framework class) using categories, but is it possible to have a class for which you do not control the source code, implement one of your own protocols? Not only do I want it to respond to certain messages sent to the instance, but also, ideally, I wanted the objects of this class to return true when checking the execution types when requesting the protocol.

+3
source share
2 answers

You can define a category that matches the protocol, so you would do something like:

@interface UIWebView (MyGreatExtensions) <UITableViewDelegate>
@end

@implementation UIWebView (MyGreatExtensions)

- (CGFloat)tableView: (UITableView *)tableView heightForRowAtIndexPath: (NSIndexPath *)indexPath {
  return 42.0;
}

// ...

@end

, , , - (, ), , ( , ).

.

+8

, . Objective-C ( NSUndoManager ), NSObject forwardInvocation:, , . , .

, , , NSObject, ToProtocol: :

+ (BOOL)conformsToProtocol:(Protocol *)aProtocol {
    if (aProtocol == @protocol(MyDynamicallyImplementedProtocol))
        return YES;
    return [super conformsToProtocol:aProtocol];
}

, , NSObject instanceRespondToSelector: *:. NSObject , .

+1

All Articles