Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iPhone, is using isKindOfClass considered bad practice in any way?

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?

like image 669
Robert Avatar asked Feb 06 '11 11:02

Robert


2 Answers

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

like image 57
Costique Avatar answered Sep 21 '22 00:09

Costique


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

like image 29
lxt Avatar answered Sep 20 '22 00:09

lxt