Variable number of method parameters in Objective C - Need an example

后端 未结 2 1303
被撕碎了的回忆
被撕碎了的回忆 2021-01-06 05:58

From Objective C Programming Guide (Under the "Object Messaging" section),

Methods that take a variable number of parameters are also possible,

2条回答
  •  青春惊慌失措
    2021-01-06 06:35

    You can see this link.

    In your header file define the methods with three dots at the end

    -(void)yourMethods:(id)string1,...;
    

    And in you implementation file write the methods body

    -(void)yourMethods:(id)string1, ...{
    
        NSMutableArray *arguments=[[NSMutableArray alloc]initWithArray:nil];
        id eachObject;
        va_list argumentList;
        if (string1) 
        {
            [arguments addObject: string1];
            va_start(argumentList, string1); 
            while ((eachObject = va_arg(argumentList, id)))    
            {
                 [arguments addObject: eachObject];
            }
            va_end(argumentList);        
         }
        NSLog(@"%@",arguments);
    }
    

    Now call your method

    [self yourMethods:@"ab",@"cd",@"ef",@"gf",nil];
    

    NOTE: remember to put nil at the end

提交回复
热议问题