Why do we have to do [MyClass class] in Objective-C?

后端 未结 8 1499
一向
一向 2020-12-13 00:01

In Objective-C, you can invoke class methods with:

[MyClass aClassMethod];

And you can query an instance\'s kind with:

[som         


        
相关标签:
8条回答
  • 2020-12-13 00:45

    MyClass is not of type Class.

    [MyClass class] is of type Class.

    If you are familiar with Java, the concept is the same.

    java.lang.String is not of type java.lang.Class

    java.lang.String.getClass() is of type java.lang.Class

    0 讨论(0)
  • 2020-12-13 00:48

    @yehnan captures it well, but I'll expand on this a little. Yes, the compiler could be modified to automatically convert a class identifier into its applicable Class in places where it is an argument rather than only when it is the target of a message. But there's not a lot of call for that kind of added complexity in the compiler (translated: slower, harder to detect coding errors). You shouldn't be calling things that return Class very often. If you are, then your object model is broken. Class-checking should be the last, desperate approach after everything else has failed (most notably correct typing and then respondsToSelector:). So for this kind of rare event, it doesn't make a lot of sense to complicate the compiler this way.

    0 讨论(0)
提交回复
热议问题