What is the difference between class and instance methods?

后端 未结 18 2164
说谎
说谎 2020-11-21 11:55

What\'s the difference between a class method and an instance method?

Are instance methods the accessors (getters and setters) while class methods are pretty much ev

18条回答
  •  被撕碎了的回忆
    2020-11-21 12:45

    In Objective-C all methods start with either a "-" or "+" character. Example:

    @interface MyClass : NSObject
    // instance method
    - (void) instanceMethod;
    
    + (void) classMethod;
    @end
    

    The "+" and "-" characters specify whether a method is a class method or an instance method respectively.

    The difference would be clear if we call these methods. Here the methods are declared in MyClass.

    instance method require an instance of the class:

    MyClass* myClass = [[MyClass alloc] init];
    [myClass instanceMethod];
    

    Inside MyClass other methods can call instance methods of MyClass using self:

    -(void) someMethod
    {
        [self instanceMethod];
    }
    

    But, class methods must be called on the class itself:

    [MyClass classMethod];
    

    Or:

    MyClass* myClass = [[MyClass alloc] init];
    [myClass class] classMethod];
    

    This won't work:

    // Error
    [myClass classMethod];
    // Error
    [self classMethod];
    

提交回复
热议问题