What is the difference between class and instance methods?

后端 未结 18 2166
说谎
说谎 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:33

    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];
    

    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.

提交回复
热议问题