iPhone,使用isKindOfClass被认为坏的做法在任何方面? [英] iPhone, is using isKindOfClass considered bad practice in any way?

查看:165
本文介绍了iPhone,使用isKindOfClass被认为坏的做法在任何方面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,如果有一个'handle all'类型的方法...

For example if there is a 'handle all' type method...

if ([obj isKindOfClass:class1]) {
    // ...
} else if ([obj isKindOfClass:class2]) {
    // etc..

这是不好的做法吗?

在运行时,可读性,可维护性或任何事情上都有缺点吗?

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:是一个有用的检查类继承的方法。它回答了唯一的问题,是一个类的对象(是一个给定类的子类)。它不回答任何其他问题,如此对象是否以自己的方式实现该方法?或我可以使用对象为X或Y?。如果你使用 isKindOfClass:作为预期,你不会有任何问题。毕竟,在动态类型语言中,你应该有工具来提取有关对象的元信息。 isKindOfClass:只是可用工具之一。

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?

主要的是,你应该总是记得使用正确的工具 为任何给定的目的。例如, isKindOfClass:不能替代 responsesToSelector: conformsToProtocol:

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

这篇关于iPhone,使用isKindOfClass被认为坏的做法在任何方面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆