自定义NSObject类,实例化如[CustomObj customObjWithData:data]

gle*_*age 0 memory-management objective-c nsobject ios

可能重复:
创建新实例的类方法

我想知道如何模拟像NSString,NSArray这样的类的实例化,如下所示:[NSArray arrayWithObject:object] ...希望消除inits和allocs.

我可能不熟悉实际做的事情.根据文档,[NSSArray数组]创建并返回一个空数组.这究竟意味着什么,任何分配?

我希望能够有一个自定义的NSObject类并执行:[CustomObj customObjWithData:data]

谢谢!

jle*_*ehr 5

首先编写相应的自定义init...方法:

- (id)initWithFoo:(Foo *)aFoo
{
     // Do init stuff.
}
Run Code Online (Sandbox Code Playgroud)

然后添加一个调用的自定义工厂方法alloc和您的自定义init...方法:

+ (id)customObjWithFoo:(Foo *)aFoo
{
    return [[[self alloc] initWithFoo:aFoo] autorelease];
}
Run Code Online (Sandbox Code Playgroud)

如果使用ARC进行编译,请忽略该autorelease调用.