1

I have a dictionary of objects which are composed of UITextfield, UITextView and UILabel, they all have the text property. Now I need to get that without using an ugly approach, which is also my current code as of now:

NSString *text = @"";

if ( [obj isKindOfClass:[UITextView class]] ) {
    text = [(UITextView *)obj text];
}
else if ( [obj isKindOfClass:[UITextField class]] ) {
    text = [(UITextField *)obj text];
}
else if ( [obj isKindOfClass:[UILabel class]] ) {
    text = [(UILabel *)obj text];
}

[array addObject:text];

Is there a way to make this shorter?

Bryan P
  • 4,142
  • 5
  • 41
  • 60
  • to shorten the code, just cast to `id` instead of your specific classes, so you won't need the `ifs` -- you should be 100% sure that your objects are only of the types you mentioned. – sergio Jun 09 '14 at 07:20
  • Well yes but I generally don't trust id so I always put extra measures :D – Bryan P Jun 09 '14 at 07:24

1 Answers1

5

I believe you're looking for respondsToSelector:

All you have to do is conditionally set the variable based on wether or not your object responds to the selector text.

NSString *text = nil;

if ([obj respondsToSelector:@selector(text)]) {
    text = [obj text];

    if (text) {
        [array addObject:text];
    }
}

And as @Hemang points out, you can find more information on when to use respondsToSelector: here: when to use respondsToSelector in objective-c

Community
  • 1
  • 1
Mick MacCallum
  • 129,200
  • 40
  • 280
  • 281