类方法和实例方法有什么区别? [英] What is the difference between class and instance methods?
问题描述
类方法和实例方法有什么区别?
What's the difference between a class method and an instance method?
实例方法是访问器(getter 和 setter),而类方法几乎是其他所有东西吗?
Are instance methods the accessors (getters and setters) while class methods are pretty much everything else?
推荐答案
就像大多数其他答案所说的那样,实例方法使用类的实例,而类方法可以只使用类名.在 Objective-C 中,它们是这样定义的:
Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:
@interface MyClass : NSObject
+ (void)aClassMethod;
- (void)anInstanceMethod;
@end
然后可以像这样使用它们:
They could then be used like so:
[MyClass aClassMethod];
MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];
类方法的一些真实示例是许多基础类中的便捷方法,例如 NSString
的 +stringWithFormat:
或 NSArray
的+arrayWithArray:
.一个实例方法是 NSArray
的 -count
方法.
Some real world examples of class methods are the convenience methods on many Foundation classes like NSString
's +stringWithFormat:
or NSArray
's +arrayWithArray:
. An instance method would be NSArray
's -count
method.
这篇关于类方法和实例方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!