我想向我的自定义对象添加一个便利构造函数。 类似于[NSArray arrayWithArray:]
如何编写一个Objective-C的便利构造函数
我知道它涉及一个返回自动释放对象的类方法。我一直在google搜索,但我似乎可以找到的一个方便的构造函数的定义,但不是如何写一个。
我想向我的自定义对象添加一个便利构造函数。 类似于[NSArray arrayWithArray:]
如何编写一个Objective-C的便利构造函数
我知道它涉及一个返回自动释放对象的类方法。我一直在google搜索,但我似乎可以找到的一个方便的构造函数的定义,但不是如何写一个。
比方说,你有以下几种:
@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];
}
编辑:替换为id
与instancetype
。它们在功能上是完全相同的,但后者为编译器提供了关于方法返回类型的更好的提示。
-(MYClass*) myInit{
self = [super init];
/* Your code */
return self;
}
假设你从NSObject派生你的类。
只要给它任何你想传递给构造函数的参数。
通常我的方法如下:首先我创建一个普通的初始化方法(实例方法),然后创建一个调用普通初始化方法的类方法。在我看来,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
+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
@albertamg:没错。 :) –
希望谷歌索引它这次;) –