In this post let's see the difference that makes by initializing an object using,
MyClass *obj = [[MyClass alloc] init];
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 alloc] init];
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 alloc] initWithDescription:@"desc.."];
Hope this post is useful. Fell free to comment incase of any queries.
No comments:
Post a Comment