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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With