Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use something like (id<UISearchBarDelegate>)self?

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.

like image 973
Perlguy Avatar asked Nov 18 '25 15:11

Perlguy


1 Answers

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)).

like image 181
Wain Avatar answered Nov 20 '25 07:11

Wain



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!