2011-08-12 38 views

回答

33

比方说,你有以下几种:

@class PotatoPeeler : NSObject 
- (instancetype)initWithWidget: (Widget *)w; 
@end 

然后添加一个工厂方法,你就改成这样:

@class PotatoPeeler : NSObject 
+ (instancetype)potatoPeelerWithWidget: (Widget *)w; 
- (instancetype)initWithWidget: (Widget *)w; 
@end 

以及实现,简直是:

+ (instancetype)potatoPeelerWithWidget: (Widget *)w { 
    return [[[self alloc] initWithWidget: w] autorelease]; 
} 

编辑:替换为idinstancetype。它们在功能上是完全相同的,但后者为编译器提供了关于方法返回类型的更好的提示。

+12

+1注意使用'而不是self'硬编码的类名来的alloc-初始化实例,以**手柄子类正确**('这里self'指类对象本身)。还要注意返回类型'id':[“便利构造函数的返回类型是id,原因是它是初始化方法的id”](http://developer.apple.com/library/mac/documentation/Cocoa/概念/ ObjectiveC /章/ ocAllocInit.html#// apple_ref/doc/uid/TP30001163-CH22-SW12) – albertamg

+0

@albertamg:没错。 :) –

+1

希望谷歌索引它这次;) –

-4
-(MYClass*) myInit{ 
    self = [super init]; 

    /* Your code */ 

    return self; 
} 

假设你从NSObject派生你的类。

只要给它任何你想传递给构造函数的参数。

4

通常我的方法如下:首先我创建一个普通的初始化方法(实例方法),然后创建一个调用普通初始化方法的类方法。在我看来,Apple大部分时间都使用相同的方法。举个例子:

@implementation SomeObject 

@synthesize string = _string; // assuming there's an 'string' property in the header 

- (id)initWithString:(NSString *)string 
{ 
    self = [super init]; 
    if (self) 
    { 
     self.string = string; 
    } 
    return self; 
} 

+ (SomeObject *)someObjectWithString:(NSString *)string 
{ 
    return [[[SomeObject alloc] initWithString:string] autorelease]; 
} 

- (void)dealloc 
{ 
    self.string = nil; 

    [super dealloc]; 
} 

@end 
相关问题