类方法和实例方法的区别?

Tir*_*rth 1 objective-c

当我在编程中使用实例方法和类方法时,我总是很困惑.请告诉我实例方法和类方法之间的区别以及彼此的优点.

Jer*_*myP 11

所有其他答案似乎都被现已修复的错误标记所捕获.

在Objective-C中,实例方法是在将消息发送到类的实例时调用的方法.所以,例如:

id foo = [[MyClass alloc] init];
[foo someMethod];
//   ^^^^^^^^^^   This message invokes an instance method.
Run Code Online (Sandbox Code Playgroud)

在Objective-C中,类本身就是对象,而类方法只是在将消息发送到类对象时调用的方法.即

[MyClass someMethod];
//       ^^^^^^^^^^   This message invokes a class method.
Run Code Online (Sandbox Code Playgroud)

请注意,在上面的示例中,选择器是相同的,但是因为在一种情况下它被发送到MyClass的实例,而在另一种情况下它被发送到MyClass,所以调用不同的方法.在接口声明中,您可能会看到:

@interface MyClass : NSObject
{
}

+(id) someMethod;  // declaration of class method
-(id) someMethod;  // declaration of instance method

@end
Run Code Online (Sandbox Code Playgroud)

并在实施中

@implementation MyClass

+(id) someMethod
{
    // Here self is the class object
}
-(id) someMethod
{
    // here self is an instance of the class
}

@end
Run Code Online (Sandbox Code Playgroud)

编辑

对不起,错过了第二部分.这样没有优点或缺点.这就像询问while和if之间的区别是什么,以及有什么优势.它有点无意义,因为它们是为不同目的而设计的.

类方法的最常见用法是在需要时获取实例. +alloc是一个类方法,它为您提供一个新的未初始化实例.NSString有很多类方法可以为你提供新的字符串,例如+ stringWithForma

另一个常见用途是获得单身例如

+(MyClass*) myUniqueObject
{
    static MyUniqueObject* theObject = nil;
    if (theObject == nil)
    {
        theObject  = [[MyClass alloc] init];
    }
    return theObject;
}
Run Code Online (Sandbox Code Playgroud)

上述方法也可以作为实例方法,因为Object是静态的.但是,如果将其设置为类方法并且不必首先创建实例,则语义会更清晰.


小智 5

如果我们不想创建类的对象那么我们使用类方法 如果我们想通过类的对象调用方法那么我们使用实例方法