2011-02-04 30 views
9

我希望有一種方法,我可以把儘可能多的爭論,因爲我需要像NSArray的陣列方法添加儘可能多的對象,只要我在末尾添加'nil'來告訴它我完成了。與輸入

我的問題是我怎麼知道給了多少個論據,我怎麼一次一個地去看它們呢?

回答

21
- (void)yourMethod:(id) firstObject, ... 
{ 
    id eachObject; 
    va_list argumentList; 
    if (firstObject) 
    {    
    // do something with firstObject. Remember, it is not part of the variable argument list 
    [self addObject: firstObject]; 
    va_start(argumentList, firstObject);   // scan for arguments after firstObject. 
    while (eachObject = va_arg(argumentList, id)) // get rest of the objects until nil is found 
    { 
     // do something with each object 
    } 
    va_end(argumentList); 
    } 
} 
+0

+1它幫了我,thax – 2013-09-06 09:06:00

3

我還沒有與這些可變參數方法的經驗(因爲他們是所謂的),但有一些可可的功能來對付它。

從蘋果公司的技術問答&一個QA1405(代碼片段):

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

http://developer.apple.com/library/mac/#qa/qa2005/qa1405.html

+0

呵呵......它看起來像是它的唯一權威來源(一分鐘內三個答案......) – FeifanZ 2011-02-04 02:38:00

0

複製我會試試這個:http://www.numbergrinder.com/node/35

蘋果在自己的音樂庫提供便利的訪問。知道你有多少元素的方法是迭代列表直到你打到零。我想建議,但是,如果你想傳遞可變數量的參數到你正在寫的某個方法中,只需傳遞一個NSArray並遍歷該數組。

希望這會有所幫助!