所有其他答案似乎都被现在已修复的不正确标签发现了。
在 Objective-C 中,实例方法是在向类的实例发送消息时调用的方法。所以,例如:
id foo = [[MyClass alloc] init];
[foo someMethod];
// ^^^^^^^^^^ This message invokes an instance method.
在 Objective-C 中,类本身就是对象,类方法只是在向类对象发送消息时调用的方法。即
[MyClass someMethod];
// ^^^^^^^^^^ This message invokes a class method.
请注意,在上面的示例中,选择器是相同的,但是因为在一种情况下它被发送到 MyClass 的一个实例,而在另一种情况下它被发送到 MyClass,因此调用了不同的方法。在接口声明中,您可能会看到:
@interface MyClass : NSObject
{
}
+(id) someMethod; // declaration of class method
-(id) someMethod; // declaration of instance method
@end
在实现中
@implementation MyClass
+(id) someMethod
{
// Here self is the class object
}
-(id) someMethod
{
// here self is an instance of the class
}
@end
编辑
抱歉,错过了第二部分。没有这样的优点或缺点。这就像问 while 和 if 之间有什么区别,以及一个比另一个有什么优势。这有点毫无意义,因为它们是为不同的目的而设计的。
类方法最常见的用途是在需要时获取实例。 +alloc 是一个类方法,它为您提供一个新的未初始化实例。 NSString 有很多类方法来给你新的字符串,例如+stringWithForma
另一个常见的用途是获取单例,例如
+(MyClass*) myUniqueObject
{
static MyUniqueObject* theObject = nil;
if (theObject == nil)
{
theObject = [[MyClass alloc] init];
}
return theObject;
}
上述方法也可以用作实例方法,因为 theObject 是静态的。但是,如果将其设为类方法并且不必先创建实例,则语义会更清晰。