Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I know that I can extend a class (for example a 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 custom protocols? I not only want to have it respond to certain messages if sent to an instance, but also, ideally, want objects of that class to return true on runtime type checks when querying for the protocol.

like image 443
SoftMemes Avatar asked Feb 17 '26 01:02

SoftMemes


1 Answers

You can define a category that conforms to the protocol, so you'd do something like:

@interface UIWebView (MyGreatExtensions) <UITableViewDelegate>
@end

@implementation UIWebView (MyGreatExtensions)

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

// ...

@end

A small edge case to consider is that if someone else tries to do the same thing (e.g. a third-party framework also adds the protocol via a category) then you can't guarantee that your version will be used (and of course neither can they).

More on this approach from Mark Dalrymple.


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!