new
Allocates a new instance of the receiving class, sends it an init
message, and returns the initialized object.
+ (id)new
Return Value
A new instance of the receiver.
Discussion
This method is a combination of alloc
and init
. Like alloc
, it initializes the isa
instance variable of the new object so it points to the class data structure. It then invokes the init
method to complete the initialization process.
Unlike alloc
, new
is sometimes re-implemented in subclasses to invoke a class-specific initialization method. If the init...
method includes arguments, they’re typically reflected in a new...
method as well. For example:
+ newMyClassWithTag:(int)tag data:(struct info *)data |
{ |
return [[self alloc] initWithTag:tag data:data]; |
} |
However, there’s little point in implementing a new...
method if it’s simply a shorthand for alloc
and init...
, as shown above. Often new...
methods will do more than just allocation and initialization. In some classes, they manage a set of instances, returning the one with the requested properties if it already exists, allocating and initializing a new instance only if necessary. For example:
+ newMyClassWithTag:(int)tag data:(struct info *)data |
{ |
MyClass *theInstance; |
|
if ( theInstance = findTheObjectWithTheTag(tag) ) |
return [theInstance retain]; |
return [[self alloc] initWithTag:tag data:data]; |
} |
Although it’s appropriate to define new new...
methods in this way, the alloc
andallocWithZone:
methods should never be augmented to include initialization code.
Special Considerations
If you are using managed memory (not garbage collection), this method retains the object before returning it. The returned object has a retain count of 1
and is notautoreleased. The invoker of this method is responsible for releasing the returned object, using either release
or autorelease
.
Availability
- Available in iPhone OS 2.0 and later.
Related Sample Code
Declared In
NSObject.h