alloc, init, and new in Objective-C

Objective C

Objective C Problem Overview


One book for about iPhone programming instantiates classes like this:

[[Class alloc] init]

Another book about Objective-C does it like this:

[Class new]

What's the difference?

Objective C Solutions


Solution 1 - Objective C

+new is implemented quite literally as:

+ (id) new
{
    return [[self alloc] init];
}

Nothing more, nothing less. Classes might override it, but that is highly atypical in favor of doing something like +fooWithBar:.

Solution 2 - Objective C

Originally in Objective-C, objects were created with new. As the OpenStep/Cocoa framework evolved, the designers developed the opinion that allocating the memory for an object and initializing its attributes were separate concerns and thus should be separate methods (for example, an object might be allocated in a specific memory zone). So the alloc-init style of object creation came into favor.

Basically, new is old and almost-but-not-quite deprecated — thus you'll see that Cocoa classes have a lot of init methods but almost never any custom new methods.

Solution 3 - Objective C

As already mentioned, by defaut there is no difference. But you can overwrite the new class method. Apple's documentation has some thoughts on this.

> Unlike alloc, new is sometimes > re-implemented in subclasses to invoke > a class-specific initialization > method[...] Often new... methods will > do more than just allocation and > initialization.

Solution 4 - Objective C

It depends on the Class, but [Class new] is most likely a convenience method that calls [[Class alloc] init] internally. Thus, you can not call other init methods such as "initWithString".

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionneuromancerView Question on Stackoverflow
Solution 1 - Objective CbbumView Answer on Stackoverflow
Solution 2 - Objective CChuckView Answer on Stackoverflow
Solution 3 - Objective Cuser123444555621View Answer on Stackoverflow
Solution 4 - Objective CJoshView Answer on Stackoverflow