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

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

I am a little confused in [Class new] and [[Class alloc] init] . I defined a content object 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 there must be some difference.

Please explain the differences, pros and cons of both?

+68
new-operator ios objective-c allocation init
Jun 29 2018-12-12T00:
source share
3 answers

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

Init : An instance method of NSObject. Implemented by subclasses to initialize a new object (receiver) immediately after allocating memory for it.

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

Release : NSObject delegate instance method. Decreases the recipient reference count.

Auto-release : NSObject delegate instance method. Adds the recipient to the current automatic release pool.

Save: The instance method of the NSObject delegate. Increases the recipient reference count.

Copy: the instance method of the NSObject delegate. Returns a new instance that is a copy of the recipient.

So, in conclusion, we can say that

alloc goes with init

new = alloc + init

+130
Jun 29 2018-12-12T00:
source share

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

+28
Jun 29 2018-12-12T00:
source share

Here: alloc, init and new in Objective-C

This is mainly a matter of modern and traditional. The most direct advantage of init over the new is that there are many custom init methods.

+9
Jun 29 '12 at 5:01
source share



All Articles