Objective c implement method which takes array of arguments

后端 未结 3 1147
闹比i
闹比i 2021-02-09 04:19

Hee

Does anybody know how to implement an method in objective c that will take an array of arguments as parameter such as:

[NSArray arrayWithObjects:@\"A         


        
3条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-09 05:04

    The ellipsis (...) is inherited from C; you can use it only as the final argument in a call (and you've missed out the relevant comma in your example). So in your case you'd probably want:

    + (void)doSomethingToObjects:(id)firstObject, ...;
    

    or, if you want the count to be explicit and can think of a way of phrasing it well:

    + (void)doManyTimes:(NSInteger)numberOfTimes somethingToObjects:(id)firstObject, ...;
    

    You can then use the normal C methods for dealing with ellipses, which reside in stdarg.h. There's a quick documentation of those here, example usage would be:

    + (void)doSomethingToObjects:(id)firstObject, ...
    {
        id object;
        va_list argumentList;
    
        va_start(argumentList, firstObject);
        object = firstObject;
    
        while(1)
        {
            if(!object) break; // we're using 'nil' as a list terminator
    
            [self doSomethingToObject:object];
            object = va_arg(argumentList, id);
        }
    
        va_end(argumentList);
    }
    

    EDIT: additions, in response to comments. You can't pass the various things handed to you in an ellipsis to another function that takes an ellipsis due to the way that C handles function calling (which is inherited by Objective-C, albeit not obviously so). Instead you tend to pass the va_list. E.g.

    + (NSString *)doThis:(SEL)selector makeStringOfThat:(NSString *)format, ...
    {
        // do this
        [self performSelector:selector];
    
        // make string of that...
    
        // get the argument list
        va_list argumentList;
        va_start(argumentList, format);
    
        // pass it verbatim to a suitable method provided by NSString
        NSString *string = [[NSString alloc] initWithFormat:format arguments:argumentList];
    
        // clean up
        va_end(argumentList);
    
        // and return, as per the synthetic example
        return [string autorelease];
    }
    

提交回复
热议问题