Obj-c如何继承一个方法有参数数组?

时间:2013-02-07 03:30:36

标签: ios objective-c c

我理解关键词“va_list”“va_start”“va_arg”“va_end”的用法。 我的supper类有一个init方法,如下所示:

超级班:

- (id) initWithChildren:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION{
    if(self = [super init]){
        va_list children;
        va_start(children, firstChild);

        self.children = [[NSMutableArray alloc] initWithObjects:firstChild, nil];
        firstChild.father = self;

        NSObject* child;
        while ((child = va_arg(children, NSObject*)) != nil){
            [_children addObject:child];
        }
        va_end(children);
    }
    return self;
}

效果很好。但是我很难继承它。

子类

- (id) initWithName:(NSString*)name children:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION{
    self = [super initWithChildren:"what should I write here?"];
    if (self){
        self.name = name;
        //other subclass work
    }
    return self;
}

有什么想法吗?谢谢。

1 个答案:

答案 0 :(得分:2)

为了做到这一点,你的超类需要公开一个以va_list为参数的指定初始值设定项。有关如何在标准库中完成此操作的示例,请参阅vprintf

- (id) initWithChildren:(NSObject*)firstChild, ... NS_REQUIRES_NIL_TERMINATION {
    va_list args;
    va_start(args, firstChild);
    id res = [self initWithChildren:firstChild varArg:args];
    va_end (args);
    return res;
}

- (id) initWithChildren:(NSObject*)firstChild, varArg:va_list args {
    // Do the actual initialization here
    ...
}