2011-02-04 7 views
9

Quiero tener un método en el que puedo poner tantos argumentos como que necesito como el NSArray:Método con una serie de entradas

- (id)initWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION; 

hacemos lo siguiente:

NSArray *array = [[NSArray alloc] initWithObjects:obj1, obj2, ob3, nil]; 

puedo agregue tantos objetos como quiera siempre y cuando agregue 'nil' al final para decir que he terminado.

Mi pregunta es ¿cómo sabría cuántos argumentos se dieron, y cómo los pasaría de uno en uno?

Respuesta

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 me ayudó, thax –

3

No he tenido experiencia con estos métodos variadic (como se les llama), pero hay algunas funciones de cacao para tratar con él.

partir de Apple Técnica Q & Un QA1405 (fragmento de código):

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

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

+0

Heh ... parece que es prácticamente la única fuente autorizada en él (tres respuestas en el lapso de un minuto ...) – FeifanZ

+0

También está este tutorial de Cocoa With Love http: //cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html –

0

me gustaría probar esto: http://www.numbergrinder.com/node/35

Apple proporciona acceso en sus bibliotecas para mayor comodidad. La forma de saber cuántos elementos tienes es iterando sobre la lista hasta que llegues a cero.

Lo que yo recomendaría, sin embargo, si desea pasar una cantidad variable de argumentos en algún método que está escribiendo, simplemente pase un NSArray e itere sobre esa matriz.

Espero que esto ayude!

Cuestiones relacionadas