所有其他答案似乎都被错误的标签所捕获,现已修复。
在 Objective-C 中,实例方法是当消息发送到类的实例时调用的方法。因此,例如:
id foo = [[MyClass alloc] init];
[foo someMethod];
// ^^^^^^^^^^ This message invokes an instance method.
在 Objective-C 中,类本身就是对象,类方法只是当消息发送到类对象时调用的方法。 IE。
[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
Edit
抱歉,错过了第二部分。本身没有优点或缺点。这就像问 while 和 if 之间有什么区别,以及其中一个相对于另一个的优点是什么。这有点毫无意义,因为它们是为不同的目的而设计的。
类方法最常见的用途是在需要时获取实例。+alloc
是一个类方法,它为您提供一个新的未初始化实例。 NSString 有大量的类方法来给你新的字符串,例如+stringWithForma
另一个常见用途是获取单例,例如
+(MyClass*) myUniqueObject
{
static MyUniqueObject* theObject = nil;
if (theObject == nil)
{
theObject = [[MyClass alloc] init];
}
return theObject;
}
上面的方法也可以用作实例方法,因为 theObject 是静态的。但是,如果将其设为类方法,则语义会更清晰,并且不必首先创建实例。