iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法

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...

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



  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值