iOS 知识

iOS可变参数va_list

2018-06-08  本文已影响188人  SamCheck

看一下系统UIAlertView里面的一个方法。

- (instancetype)initWithTitle:(nullable NSString *)title
message:(nullable NSString *)message 
delegate:(nullable id /*<UIAlertViewDelegate>*/)delegate 
cancelButtonTitle:(nullable NSString *)cancelButtonTitle 
otherButtonTitles:(nullable NSString *)otherButtonTitles, ... ;

在方法的最尾部有... 省略号用来添加其他弹唱按钮,看一下实现方式。

sys/_types/_va_list.h文件:

#ifndef _VA_LIST_T
#define _VA_LIST_T
#include <machine/types.h> /* __darwin_va_list */
typedef __darwin_va_list va_list;
#endif /* _VA_LIST_T */

stdarg.h文件:

#ifndef __STDARG_H
#define __STDARG_H

#ifndef _VA_LIST
typedef __builtin_va_list va_list;
#define _VA_LIST
#endif
#define va_start(ap, param) __builtin_va_start(ap, param)
#define va_end(ap)          __builtin_va_end(ap)
#define va_arg(ap, type)    __builtin_va_arg(ap, type)

/* GCC always defines __va_copy, but does not define va_copy unless in c99 mode
 * or -ansi is not specified, since it was not part of C90.
 */
#define __va_copy(d,s) __builtin_va_copy(d,s)

#if __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L || !defined(__STRICT_ANSI__)
#define va_copy(dest, src)  __builtin_va_copy(dest, src)
#endif

#ifndef __GNUC_VA_LIST
#define __GNUC_VA_LIST 1
typedef __builtin_va_list __gnuc_va_list;
#endif

#endif /* __STDARG_H */
-(void)function:(NSString*)value,...{
    va_list argumentList;
    va_start(argumentList, value);
    NSString *tmp = nil;
    
    while ((tmp = va_arg(argumentList, NSString *))) {
        NSLog(@"%@",tmp);
    }
    
    va_end(argumentList);
}

调用:

[self function:@"1",@"2",@"3",nil];

打印:

2
3

参数列表传入方法中,通过遍历argumentList数组获得少一个1,所以va_list获取的数据包含第一位数据,使用时注意。

上一篇下一篇

猜你喜欢

热点阅读