GendoIkari
GendoIkari

Reputation: 11914

How to stop warning for UIView may not respond to selector

I have a class that has a UIView as a property. Sometimes I pass in a UILabel; sometimes a UITextField. No matter which I pass in, I want the class to set the text. Currently I am doing this, which works:

if ([self.viewToUpdate respondsToSelector:@selector(setText:)] && !self.newAnswer)
    [self.viewToUpdate setText:[[self.choices objectAtIndex:indexPath.row] text]];

The problem is, this gives a warning, because even though I'm checking respondsToSelector, Xcode doesn't know that my UIView will respond to setText:. How can I remove this warning?

I know that I can specifically check to see if it's a TextField or a Label, and then cast to a TextField or a Label, respectively, but this would be a pain, and if I ever have more types of views, I'd have to add a few more lines of code for each one.

I thought about creating my own protocol, and then having my class have id as the type for viewToUpdate... but of course UITextField and UILabel wouldn't conform to that protocol...

Upvotes: 9

Views: 2667

Answers (1)

Sam Ritchie
Sam Ritchie

Reputation: 11038

try just casting it as an id:

if ([self.viewToUpdate respondsToSelector:@selector(setText:)] && !self.newAnswer)
    [(id)self.viewToUpdate setText:[[self.choices objectAtIndex:indexPath.row] text]];

Upvotes: 16

Related Questions