iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法

原文出自http://blog.csdn.net/worn_nest/article/details/7993018

1.很早就看到项目里面有下面这样的写法

  1. - (id) initWithTitle:(NSString *)title items:(MXContextMenuItem *)item, ... NS_REQUIRES_NIL_TERMINATION;  

2.查了点资料,自己练习了下,试着写了个

  1. //.h  
  2. - (NSString *)addMoreArguments:(NSString *)firstStr,...NS_REQUIRES_NIL_TERMINATION;  
  3.   
  4. //.m  
  5. - (NSString *)addMoreArguments:(NSString *)firstStr,...  
  6. {  
  7.     va_list args;  
  8.     va_start(args, firstStr); // scan for arguments after firstObject.  
  9.       
  10.     // get rest of the objects until nil is found  
  11.     NSMutableString *allStr = [[[NSMutableString alloc] initWithCapacity:16] autorelease];  
  12.     for (NSString *str = firstStr; str != nil; str = va_arg(args,NSString*)) {  
  13.         [allStr appendFormat:@"* %@ ",str];  
  14.     }  
  15.       
  16.     va_end(args);  
  17.     return allStr;  
  18. }  
  19.   
  20. //test  
  21. NSString *str = [self addMoreArguments:@"hello",@"world",@"this",@"is",@"a",@"test", nil];  
  22. NSLog(@"str = %@",str);  
  23. //output: str = * hello * world * this * is * a * test  

3.

官方有个例子挺好的,实现NSMutableArray的appendObjects...

appendObjects实现

code:

  1. #import <Cocoa/Cocoa.h>  
  2.   
  3. @interface NSMutableArray (variadicMethodExample)  
  4.   
  5. - (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.  
  6.   
  7. @end  
  8.   
  9. @implementation NSMutableArray (variadicMethodExample)  
  10.   
  11. - (void) appendObjects:(id) firstObject, ...  
  12. {  
  13. id eachObject;  
  14. va_list argumentList;  
  15. if (firstObject) // The first argument isn't part of the varargs list,  
  16.   {                                   // so we'll handle it separately.  
  17.   [self addObject: firstObject];  
  18.   va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.  
  19.   while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"  
  20.       [self addObject: eachObject]; // that isn't nil, add it to self's contents.  
  21.   va_end(argumentList);  
  22.   }  
  23. }  
  24.   
  25. @end  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值