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
I think the best way to understand this is to look at alloc
and init
. It was this explanation that allowed me to understand the differences.
Class Method
A class method is applied to the class as a whole. If you check the alloc
method, that's a class method denoted by the +
before the method declaration. It's a class method because it is applied to the class to make a specific instance of that class.
Instance Method
You use an instance method to modify a specific instance of a class that is unique to that instance, rather than to the class as a whole. init
for example (denoted with a -
before the method declaration), is an instance method because you are normally modifying the properties of that class after it has been created with alloc
.
Example
NSString *myString = [NSString alloc];
You are calling the class method alloc
in order to generate an instance of that class. Notice how the receiver of the message is a class.
[myString initWithFormat:@"Hope this answer helps someone"];
You are modifying the instance of NSString
called myString
by setting some properties on that instance. Notice how the receiver of the message is an instance (object of class NSString
).