2013-02-07 20 views
4

我瞭解關鍵詞「va_list」「va_start」「va_arg」「va_end」的用法。 和我吃晚飯類有一個init方法是這樣的:Obj-c如何繼承一個方法有參數數組?

超級類:

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

它的工作原理well.But我有麻煩要繼承它。

子類

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

任何想法?謝謝。

回答

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 
    ... 
} 
+0

這是所有討論的副本。 :) – rmaddy

+1

@rmaddy我只是在發佈答案後纔看到了這個愚人節。不幸的是,當您輸入答案時,SO不會顯示傳入的錯誤。 – dasblinkenlight