通过类名与自身调用类方法 [英] Calling class methods via class name vs self
问题描述
假设我们有一个名为 Calculator
的类.其中有一个类方法,称为runProgram
.如果我想调用这个类的方法,在类的实现里面,这两者有什么区别:
Suppose we have a class named Calculator
. There's a class method in it, called runProgram
.
If I wanted to call this class method, inside the class's implementation, what would the difference between these two be:
[Calculator runProgram]
或
[self runProgram]
这两个是一样的吗?
推荐答案
如果在实例方法中:
[self runProgram]
这里的self
表示对象实例本身,因此会产生运行时错误.你要使用
in this, self
means the object instance itself, and thus it will generate a runtime error. You want to use
[[self class] runProgram]
相反.
但是,如果你从另一个类方法调用这个方法,那么
However, if you call this method from another class method, then
[self runProgram]
是正确的,因为现在 self
指的是类本身.我不鼓励使用
is correct, since now self
refers to the class itself. I'd discourage to use
[Calculator runProgram]
因为类的子类会错误地调用超类(Calculator
)的方法,而不是可能被覆盖的方法.
because then subclasses of the class would erroneously call the superclass' (Calculator
's) method instead of a possibly overridden method.
这篇关于通过类名与自身调用类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!