72

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?

Community
  • 1
  • 1
Prasad G
  • 6,702
  • 7
  • 42
  • 65

3 Answers3

134

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

Community
  • 1
  • 1
Shantanu
  • 3,086
  • 3
  • 25
  • 32
29

The +new method is simply shorthand for +alloc and -init. The ownership semantics are identical. The only benefit to using +new is that it is more concise. If you need to provide arguments to the class's initialiser, you will have to use the +alloc and -initWith... methods instead.

dreamlax
  • 93,976
  • 29
  • 161
  • 209
9

Here: alloc, init, and new in Objective-C

Basically it's a question of modern versus traditional. The most direct advantage of init over new is that there are many custom init methods.

Community
  • 1
  • 1
OFRBG
  • 1,653
  • 14
  • 28