Whats the difference between class methods and Instance methods. Why do we need them separately?
Can somebody please explain?
Class and Instance Methods
• Instances respond to instance methods
- (id)init;
- (float)height;
- (void)walk;
• Classes respond to class methods
+ (id)alloc;
+ (id)person;
+ (Person *)sharedPerson;
Taimur
An instance method is only available on an instance of the class, while a class method does not need an instance but is available on the class.
Class Methods are denoted by a
+while instance methods are denoted by a-before their return type.Let’s take
NSObjectfor example.NSObjecthas a class method named+ (id)alloc. The alloc method is used to allocate an instance of the class. Obviously alloc must be a class method because if it was an instance method, where would you get the “root” instance from?On the other hand
- (id)initis an instance method because it initializes the state of an instance.