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.
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 returnautorelease
objects, or singleton accessors.Consider the
length
method inNSString
. 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 ofNSString
what its length is. AskingNSString
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 ofNSNumber
that is independent of any specific instance.