Friday, May 20, 2016

Objective-C Class methods vs Instance methods

A Class method is a method that operates on the class objects rather than instances of the class.
Where as, An Instance method is a method that operates on the instance object.

     @interface MyCustomClass : NSObject

          + (NSString *)classMedthod;
          - (NSString*)instanceMethod;


In Objective-C, a class method is denoted by a plus (+) sign at the beginning of the method declaration and implementation. Instance methods is denoted by normal minus (-) sign.

+ (NSString*)classMedthod{

           return @"classMedthod";

We can not class methods with the class objects. We can only call them with the class.

NSString *userName = 1; 

Some class methods of native classes,

[NSString stringWithFormat:];
    [NSString string];
    [NSArray array];
    [NSArray arrayWithObjects:];
    [NSMutableArray array];

Typically, these class methods returns the object of same type.

[NSString string];                        // returns NSString
     [NSArray arrayWithObjects:];     // returns NSArray
     [NSMutableArray array];            // returns NSMutableArray

We can go for class methods for our custom classes If we don't want our class instances should change something instead we want to give the authority to class itself.


I have a Child class, I don't want my child instances to plan for a trip, Only the Child class can plan for a trip. In this case we can go for a class method called 'planForATrip'.

@interface Child : NSObject

        + (void)planForATrip:(BOOL)plan;
        - (NSString*)study;
        - (NSString*)listenToMusic;
        - (NSString*)play;


Hope this post is useful. Feel free to comment in case of any queries.