I've been browsing Sketch, an example program they ship with Xcode, and I keep seeing thi开发者_StackOverflow中文版ngs like this (not always though):
[[MyClass class] classMethod]
Now, since MyClass
isn't an instance of the class, I would just do:
[MyClass classMethod]
As an experiment though, I was able to make a difference between the two above statements, by overriding + (Class)class
and returning another class! If you ever want to do this, you would need the former version for it to work, so I can see that there could be a usage for this, but is there really?
It sounds like an awful idea tampering like this with +class
, but please enlighten me if there is. Thanks!
To see some examples, check out the method -copy:
in SKTGraphicsView.m
in the Sketch program found in Developer/Examples/Sketch/
.
In the case that you cited, I don't really see any good reason for calling +class
. However, there is definitely a case for calling [[self class] doSomething]
instead of [[MyClass class] doSomething]
. In the first case, [self class]
can return the correct result if the object has been subclassed. In the second case, you will always get the MyClass
class object, which means that MySubClass
could not effectively override the +doSomething
class method.
There is no good reason for using +class
in that case. +class
simply returns the object (the class object) that it is called on, same as -self
. In most cases, people use [SomeClass class]
to get the class object for a class, because the name of a class is not an expression, and can only be used as the receiver in the message calling syntax as a special case. Therefore, in all other contexts, they use [SomeClass class]
to get the class object as an expression (although [SomeClass self]
would also work equally well).
In the case you showed, it is redundant, because it is the receiver of a message. I am guessing they did it out of habit or ignorance (they thought that you must always write [SomeClass class]
to use the class).
精彩评论