new

本文介绍Objective-C中使用new方法创建并初始化对象的过程。new方法结合了alloc和init的功能,并在某些子类中进行了重写以实现特定的初始化逻辑。

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 isainstance 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 allocnew 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 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值