Purpose of Instance Methods vs. Class Methods in Objective-C
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.
Related videos on Youtube
pasawaya
Updated on September 15, 2022Comments
-
pasawaya over 1 year
I have checked out all these questions...
- Difference Class and Instance Methods
- Difference between class methods and instance methods?
- What is the difference between class and instance methods?
...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 almost 12 yearsYou 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 almost 10 yearsGood explanation. But I wonder if it still matter now since that when I write this post, ARC already in picture.
-
Aldee almost 9 yearsExcellent explanation.
-
Azure Yu over 7 yearsNice Explanation. You really got the main reason!