zoukankan      html  css  js  c++  java
  • iOS 多参数 ...NS_REQUIRES_NIL_TERMINATION 的写法

    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  
  • 相关阅读:
    浅谈Java的开放封闭原则
    Gson 和 Fastjson 你不知道的事
    mac 开发必备软件(不断update ing...)
    fastJson泛型如何转换
    springboot 学习笔记(二)--- properties 配置
    springboot 学习笔记(一)
    mac 安装MySQL
    mybatis 注解快速上手
    svn 冲突解决
    java画图输出到磁盘
  • 原文地址:https://www.cnblogs.com/ubersexual/p/3526199.html
Copyright © 2011-2022 走看看