Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between [Class new] and [[Class alloc] init] in iOS? [duplicate]

Possible Duplicate:
alloc, init, and new in Objective-C

I am a little confused about [Class new] and [[Class alloc] init]. I have defined an object content using [Class new] and [[Class alloc] init].

(1). NSMutableArray *content = [NSMutableArray new]; (2). NSMutableArray *content = [[NSMutableArray alloc] init]; 

My question is about the differences between [Class new] and [[Class alloc] init]. For me, (1) and (2) are similar. If (1) and (2) are similar, then why do we use [[Class alloc] init] most of the time, compared to [Class new]? I think that there must be some difference.

Kindly explain the differences, pros & cons of both?

like image 201
Prasad G Avatar asked Jun 29 '12 04:06

Prasad G


People also ask

What is Alloc and init in Objective C?

Alloc allocates memory for the instance, and init gives it's instance variables it's initial values. Both return pointers to the new instance, hence the method chain.

What is Alloc in Swift?

This is an instance variable of the new instance that is initialized to a data structure describing the class; memory for all other instance variables is set to 0 . You must use an init... method to complete the initialization process. For example: TheClass *newObject = [[TheClass alloc] init];

What does Alloc mean in Objective C?

In its simplest form: alloc: short for allocation, reservers a memory location and returns the pointer to that memory location. This pointer is then stored in the k variable. init: short for initialization, sets up the object and returns the object.

What is new in Objective C?

A new type has been added to Objective-C, aptly named instancetype. This can only be used as a return type from an Objective-C method and is used as a hint to the compiler that the return type of the method will be an instance of the class to which the method belongs.


1 Answers

Alloc: Class method of NSObject. Returns a new instance of the receiving class.

Init: Instance method of NSObject. Implemented by subclasses to initialize a new object (the receiver) immediately after memory for it has been allocated.

New: Class method of NSObject. Allocates a new instance of the receiving class, sends it an init message, and returns the initialized object.

Release: Instance method of NSObject delegate. Decrements the receiver’s reference count.

Autorelease: Instance method of NSObject delegate. Adds the receiver to the current autorelease pool.

Retain: Instance method of NSObject delegate. Increments the receiver’s reference count.

Copy: Instance method of NSObject delegate. Returns a new instance that’s a copy of the receiver.

So to conclude we can say that

alloc goes with init

new = alloc + init

like image 179
Shantanu Avatar answered Sep 24 '22 04:09

Shantanu