2

假设我有一个指定的初始化器,它可以像这样进行一些初始化:

- (id)initWithBlah:(NSString *)arg1 otherBlah:(NSArray *)arg2
{ 
    if (self = [super init])
    {
        ...
    }
    return self;
}

我有另一个初始化程序需要调用它,然后执行一些其他设置任务:

- (id)initWithSomeOtherBlah:(void *)creativeArg
{
    // Is this right? It seems to compile and run as expected, but feels wrong
    self = [self initWithBlah:nil otherBlah:nil];
    if (self)
    {
        [self someProcessingForThisInitDependentOnSelfInit:creativeArg];
    }

    return self;
}

既然测试是为了确保返回值是正确的,那么在这种情况下应该使用'self'吗?我想知道这是否甚至是事件的有效组合。我们有一个初始化程序需要在指定初始化程序运行后执行一些额外设置的情况。

我想知道正确的方法是否是将这个额外的处理推到指定的初始化程序中。

如果需要更多说明,请告诉我。我试图保持简单。:)

谢谢!

4

3 回答 3

5

A general rule of thumb that I follow is that the designated initializer is the initializer with the most parameters and the other initializers chain down to the designated initializer.

In your example you are not using creativeArg in your initWithSomeOtherBlah constructor. I am not sure if that was intentional or not.

With this approach you are being explicit with your intentions when creating an object instead of side effect programming.

For example:

@implementation BlaClass

- (id)initWithBlah:(NSString *)arg1 otherBlah:(NSArray *)arg2 creativeArg:(void *)arg3
{
    if (self = [super init])
    {
        self.arg1 = arg1;
        self.arg2 = arg2;
        self.arg3 = arg3;
        [self someProcessingForThisInitDependentOnSelfInit:arg3];
    }
    return self;
}


- (void)someProcessingForThisInitDependentOnSelfInit:(void *)creativeArg
{
    if(creativeArg == NULL) return; 


    //do creative stuff 
}

- (id)initWithSomeOtherBlah:(void *)arg
{
    return [self initWithBlah:nil otherBlah:nil creativeArg:arg];
}

 ...
 @end
于 2012-06-16T04:50:27.147 回答
0

如果您的类中需要两个初始化器,它们对类的初始化有所不同,一个好的编码实践是识别两个初始化器需要执行它们的设置任务,并将它们移动到单独的方法中。这样,您无需在另一个内部调用一个自定义初始化程序。以下是您需要执行的操作:

-(void) setupBlah
{.....}

- (id)initWithBlah:(NSString *)arg1 otherBlah:(NSArray *)arg2
{ 
    if (self =[super init])
      {
        [self setupBlah];
        //Do other initialization
            ....
       }
   return self;
}

- (id)initWithSomeOtherBlah:(void *)creativeArg
{


    if (self = [super init])
    {
        [self setupBlah];
        //Do other initialization
          .....
    }

    return self;
}
于 2012-06-16T05:15:47.793 回答
0

从非指定初始化程序调用另一个初始化程序没有任何问题,请参阅此处的 Apple 文档。

如果我有两个或多个指定的初始化程序(例如带有initWithFrame:and的视图initWithCoder:),我发现自己定义了一个setUp从两个初始化程序调用的方法,这只是您的someProcessingForThisInitDependentOnSelfInit方法的较短名称。

于 2012-06-16T08:05:55.763 回答