简体   繁体   English

如何合并+ alloc和-init?

[英]How to merge +alloc and -init?

I am writing a method for a subclass of NSObject that merges the common NSObject methods "+alloc" and "-init". 我正在为NSObject的子类编写一个方法,它合并了常见的NSObject方法“+ alloc”和“-init”。 This is to save time when creating instances of a class. 这是为了在创建类的实例时节省时间。

(This subclass is also an abstract class. It is like a replacement for subclassing NSObject, so the method must be compatible with subclassing.) (这个子类也是一个抽象类。它类似于子类化NSObject的替代,因此该方法必须与子类兼容。)

For a method "make", is this the best way of writing it: 对于方法“make”,这是编写它的最佳方式:

+(id)make
{
    id newObject = [[self.class alloc] init];

    return newObject;
}

If there is a better way, what would it be? 如果有更好的方法,它会是什么?

Thanks 谢谢

更好的方法是使用+new ,已经存在:)

你可以使用[self.class new] ,它与调用[[self.class alloc] init]

我发现new作品非常好。

SomeObject *object = [SomeObject new];

in order to make simple: 为了简单起见:

id newObject = [[self alloc] init];

you can replace it with: 你可以用以下代替它:

id newObject = [self new];

But remeber that in many defined objects you can use other initializers, then you need to use: 但请记住,在许多已定义的对象中,您可以使用其他初始值设定项,然后您需要使用:

...alloc] init...]

structure. 结构体。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM