IOS - how to get a delegate class
You can (and should) use responsesToSelector to check if this delegate can respond to this selector, instead of trying to figure out its class.
Example:
if ([self.delegate respondsToSelector:@selector(method1:)]) {
[self.delegate method1:self];
} else if ([self.delegate respondsToSelector:@selector(method2:)]) {
[self.delegate method2:self];
}
And you only implement each method in the classes you want, but both are in the delegate protocol. Does this approach fit your needs?
As with other comment and response contributors, anyone who names a delegate does not need to know what class or type it is, only needs to check if that delegate conforms to the protocol and if it is responding to the method you want to call it.
More information on responsesToSelector @ Apple Documentation
source to share
The whole point of using delegate protocols is to decouple the object doing the work from the class type that acts on the work done.
In fact, the very nature of a delegate is that you don't care what class it is. You don't care that it conforms to the protocol and therefore will have a set of known functions that can run on it.
A delegate may be UIView
, UIViewController
, UILabel
or any custom class that you want.
By defining a class and then acting on it differently depending on the class, you are violating a fundamental principle that delegates and protocols try to bypass, in the first place, these are tightly coupled objects.
In addition, a class with a delegate does not need to know what is happening with the data, and that should not worry either. A UITableView
, for example, doesn't know what happens when its delegate responds to the selected cell. This delegate can update something in CoreData or move to a new ViewController. The table view does not (and should not) know this.
Your object is to say something like ... HELLO DELEGATE! Something just happened and this is the result, just wanted to let you know
. The delegate then takes that result and acts on it.
source to share