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