2011-10-08 1 views

答えて

13

あなた@interfaceに、このようなメソッドを宣言します。

- (id)myObjectWithObjects:(id)firstObject, ... NS_REQUIRES_NIL_TERMINATION; 

次に@implementationにあなたはこのようにそれを定義します

- (id)myObjectWithObjects:(id)firstObject, ... 
{ 
    va_list args; 
    va_start(args, firstObject); 
    for (id arg = firstObject; arg != nil; arg = va_arg(args, id)) 
    { 
     // Do something with the args here 
    } 
    va_end(args); 

    // Do more stuff here... 
} 

va_listva_startva_argva_endは、すべての標準的なCです可変引数を扱うための構文それらを簡単に説明する:

  • va_list - 可変引数のリストへのポインタ。
  • va_start - 指定された引数の後に最初の引数を指すようにva_listを初期化します。
  • va_arg - リストの次の引数を取り出します。引数の型を指定する必要があります(va_argに抽出するバイト数が分かるように)。
  • va_end - va_listデータ構造によって保持されているメモリを解放します。

より良い説明のために、この記事をチェックアウト - Variable argument lists in Cocoa


も参照してください:Apple Technical Q&A QA1405 - Variable arguments in Objective-C methodsから"IEEE Std 1003.1 stdarg.h"


別の例を:

@interface NSMutableArray (variadicMethodExample) 

- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects. 

@end 

@implementation NSMutableArray (variadicMethodExample) 

- (void) appendObjects:(id) firstObject, ... 
{ 
    id eachObject; 
    va_list argumentList; 
    if (firstObject) // The first argument isn't part of the varargs list, 
    {         // so we'll handle it separately. 
     [self addObject: firstObject]; 
     va_start(argumentList, firstObject); // Start scanning for arguments after firstObject. 
     while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id" 
      [self addObject: eachObject]; // that isn't nil, add it to self's contents. 
     va_end(argumentList); 
    } 
} 

@end 
+0

おかげで、受け入れました。私がhttp://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.htmlを見つけたことを追加して、stdargの使用が必要であることを読者に伝える答えを編集するといいでしょう。とにかく、巨大な感謝は、StackOverflowが私を許可するとすぐに受け入れます。 – Matoe

+0

@マトーは、チップのおかげでやります。 – chown

関連する問題