在 Objective-C 中调用指定的初始值设定项后,如何执行额外的初始化?(自我 = [自我.



假设我有一个指定的初始值设定项,它执行一些初始化:

- (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"?我想知道这是否是事件的有效组合。我们有一个初始值设定项,需要在运行指定的初始值设定项后执行一些额外的设置。

我想知道正确的方法是否是在指定的初始值设定项中推送此附加处理。

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

谢谢!

我遵循的一般经验法则是,指定的初始值设定项是具有最多参数的初始值设定项,其他初始值设定项链接到指定的初始值设定项。

在你的例子中,

你没有在你的initWithSomeOtherBlah构造函数中使用creativeArg。我不确定这是有意还是无意。

使用这种方法,您在创建对象时明确了您的意图,而不是副作用编程。

例如:

@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

如果您的类中需要两个初始化项,它们初始化类的方式略有不同,则一个好的编码做法是确定两个初始值设定项执行它们所需的安装任务,并将它们移动到单独的方法。这样,就无需在另一个自定义初始值设定项中调用另一个自定义初始值设定项。以下是您需要如何操作:

-(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;
}

从非指定的初始值设定项调用另一个初始值设定项没有错,请参阅此处的Apple文档。

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

最新更新