How to create variable argument methods in Objective-C

后端 未结 3 1666
滥情空心
滥情空心 2020-11-28 03:16

Maybe this will be obviously simple for most of you, but could you please give an example how to create similar methods (in Objective-C) and functions in C to create functio

3条回答
  •  隐瞒了意图╮
    2020-11-28 03:48

    One thing to mention here is that, the first NSString parameter here comes as format, and the other are passed in the variable argument. right? So before entering the for loop, you have one parameter to handle.

    - (NSString *) append:(NSString *)list, ...
    {
        NSMutableString * res = [NSMutableString string];
        [res appendString:list];
    
        va_list args;
        va_start(args, list);
        id arg = nil;
    
        while(( arg = va_arg(args, id))){
            [res appendString:arg];
        }
        va_end(args);
        return res;
    }
    
    - (void) test_va_arg
    {
        NSString * t = [self append:@"a", @"b", @"c", nil];
        STAssertEqualObjects(@"abc", t, @"");
    }
    

提交回复
热议问题