I've seen this in some areas of code that I am working with.
searchBar.delegate = (id<UISearchBarDelegate>)self;
My question is...
Why not just make the current class a delegate of UISearchBar by adding <UISearchBarDelegate> in the interface of the class?
Are there times when the above code is better than having the class be a delegate?.
Both ways work for me, but I'd like to learn why I may want to use one over the other.
The cast approach could be considered a cheat. It would be used if the delegate class didn't want to publicly declare the protocol conformance (but then why is it being publicly set as the delegate). Or if the delegate class didn't implement all of the required methods so declaring the protocol conformance would result in warnings.
Generally the better approach is to declare the protocol conformance (either publicly (.h) or privately (.m)).
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