Friday, August 5, 2016

Difference between [Class new] and [Class alloc] init]

In this post let's see the difference that makes by initializing an object using,


  
MyClass *obj = [[MyClass allocinit];


and using 'new'


   
MyClass *obj = [MyClass new];




   
#import "MyClass.h"

  @implementation MyClass

  +(id)alloc{
    
      NSLog(@"Allocating...");
      return [super alloc];
  }

  -(id)init{
    
      NSLog(@"Initializing...");
      return [super init];
  }

  @end



Now try with the init and new and see the log statements.



   MyClass *obj = [[MyClass allocinit];

   Allocating...
   Initializing...





   
MyClass *obj = [MyClass new];

   Allocating...
   Initializing...



Technically, both are same. The advantage of using 'new' is that it is concise.
The 'new' method is simply shorthand for alloc and init.

When there are no arguments needed for the class initializers, we can go for directly new method.
But If we need arguments for class initializers we need to go with init methods.



  -(id)initWithDescription:(NSString*)description{
    
        NSLog(@"initWithDescription...");
        return [super init];
   }


   MyClass *obj = [[MyClass allocinitWithDescription:@"desc.."];



Hope this post is useful. Fell free to comment incase of any queries.


No comments:

Post a Comment