tags:

views:

126

answers:

5

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?

+3  A: 

Nothing. new is short for alloc/init.

new is intended more for use when garbage-collection is enabled, and you don't have to worry about manual memory management. But, it works in both cases.

jtbandes
The new method has nothing to do with garbage collection. It fell out of favor years before Cocoa got garbage collection and is still not recommended even now.
Chuck
What Chuck said; +new was a leftover from NeXTSTEP and has been out of favor for years.
bbum
-1 same as what Chuck and bbum said.
JeremyP
+1  A: 

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".

Josh
No, you're still responsible for objects created with `new`.
jtbandes
@jtbandes: Josh never said you weren't.
Chuck
@Chuck: he had when I posted the comment, but looks like it was edited out quickly enough. Never mind!
jtbandes
+3  A: 

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.

Pumbaa80
+7  A: 

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.

Chuck
+2  A: 

+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:.

bbum