For example if there is a 'handle all' type method...
if ([obj isKindOfClass:class1]) {
// ...
} else if ([obj isKindOfClass:class2]) {
// etc..
Is this bad practice? Is there a neater alternative or a better way to structure the code?
Are there disadvantages in tearms of runtime, readability, maintainability or anything?
Whenever something is considered good/bad practice, it is more or less subjective. When doing something is inherently right/wrong, it is more or less objective.
isKindOfClass:
is a useful method to check class inheritance. It answers the only question, "is the object of a class which is (a subclass of) a given class?". It doesn't answer any other questions like "does this object implement that method in its own way?" or "can I use the object for X or Y?". If you use isKindOfClass:
as intended, you won't have any problems. After all, in a dynamic typed language you ought to have tools to extract meta information about objects. isKindOfClass:
is just one of the available tools.
The fact that certain objects may lie about their class should not really put you off. They just disguise themselves as objects of another class without breaking anything. And if that doesn't break anything, why should I care?
The main thing is that you should always remember to use the right tool for any given purpose. For example, isKindOfClass:
is no substitute for respondsToSelector:
or conformsToProtocol:
.
Sort of. This question basically covers what you're asking: Is it safe to use isKindOfClass: against an NSString instance to determine type?
There are some caveats you need to bear in mind (see link above), but personally I think it's a fairly readable method. You just need to make sure what you're doing inside your conditional test is appropriate (the example Apple give is along the lines of "an object may say it's a kind of NSMutableArray, but you might not be able to mutate it").
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