Does responsesToSelector use: good style?

“Is it better to style” to send a message and hope that the object is responding, or check if it responds to the selector and something like a backup, if it does not.

For instance:

- (NSString *)stringForObjectValue:(id)obj {
    if ([obj respondsToSelector:@selector(intValue)]) {
        NSString *roman = [self formatRomanNumber:[obj intValue] resultSoFar:@""];
        return roman;
    } else {
        return [NSString stringWithFormat:@"can't format a %@", [obj class]];
    }
}

against.

- (NSString *)stringForObjectValue:(id)obj {
    NSString *roman = format_roman(@"", [obj intValue]);
    return roman;
}

(example from a subclass of NSNumberFormatter ... but it can be from a subclass of NSObjectFormatter ...)

+3
source share
2 answers

If you are not 100% sure that all instances included in your function (stringForObjectValue) respond to the selector, then you must perform this check to avoid run-time failures.

, obj intValue, , . , nil , , - .

+2

, respondsToSelector: - , , , . , : Duck Typing.

+1

Source: https://habr.com/ru/post/1767694/


All Articles