1.很早就看到项目里面有下面这样的写法
- (id) initWithTitle:(NSString *)title items:(MXContextMenuItem *)item, ... NS_REQUIRES_NIL_TERMINATION;
2.查了点资料,自己练习了下,试着写了个
//.h
- (NSString *)addMoreArguments:(NSString *)firstStr,...NS_REQUIRES_NIL_TERMINATION;
//.m
- (NSString *)addMoreArguments:(NSString *)firstStr,...
{
va_list args;
va_start(args, firstStr); // scan for arguments after firstObject.
// get rest of the objects until nil is found
NSMutableString *allStr = [[[NSMutableString alloc] initWithCapacity:16] autorelease];
for (NSString *str = firstStr; str != nil; str = va_arg(args,NSString*)) {
[allStr appendFormat:@"* %@ ",str];
}
va_end(args);
return allStr;
}
//test
NSString *str = [self addMoreArguments:@"hello",@"world",@"this",@"is",@"a",@"test", nil];
NSLog(@"str = %@",str);
//output: str = * hello * world * this * is * a * test
3.
官方有个例子挺好的,实现NSMutableArray的appendObjects...
code:
#import <Cocoa/Cocoa.h>
@interface NSMutableArray (variadicMethodExample)
- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.
@end
@implementation NSMutableArray (variadicMethodExample)
- (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);
}
}
@end