Purpose of Instance Methods vs. Class Methods in Objective-C

16,407

Generally speaking, you should create instance methods when you need code that operates on a specific instance of an object. You create a class method when you need to do something that involves that class in general but probably doesn't operate on any specific objects of that class.

In practice, you will find that nearly all of your methods should be instance methods. Just take a look at any existing Objective-C class like NSString, NSArray, UIView, etc. and you'll see that the vast majority of their methods are instance methods. The most common use of class methods (again, look at the classes I mentioned) are for convenience constructors that return autorelease objects, or singleton accessors.

Consider the length method in NSString. Why is this an instance method and not a class method? It is an instance method because it only makes sense to ask a specific instance of NSString what its length is. Asking NSString in general for a length (i.e. if length was a class method) wouldn't make any sense.

On the other hand, let's say that we want to add a method to NSNumber that will return the maximum integer value that can be stored on a given system. In this case, it should be a class method because we're just asking a general question of NSNumber that is independent of any specific instance.

Share:
16,407

Related videos on Youtube

pasawaya
Author by

pasawaya

Updated on September 15, 2022

Comments

  • pasawaya
    pasawaya over 1 year

    I have checked out all these questions...

    ...and all they explain is how instance methods are used on instances of a class and class methods are used with the class, when a message is sent to a class. This is helpful, but I'm curious to know why one would use a class method vs. an instance method.

  • UIAdam
    UIAdam almost 12 years
    You are confused between method parameters and the object that is being used to call the method (a.k.a. the receiver). I'd suggest looking at some thorough Objective-C tutorials online or in a book.
  • sooon
    sooon almost 10 years
    Good explanation. But I wonder if it still matter now since that when I write this post, ARC already in picture.
  • Aldee
    Aldee almost 9 years
    Excellent explanation.
  • Azure Yu
    Azure Yu over 7 years
    Nice Explanation. You really got the main reason!