Variable argument lists in Cocoa

Spark读取hudi中的数据报Unable to infer schema for Parquet. It must be specified manually.; Exception in thread "main" org.apache.spark.sql.AnalysisException: Unable to infer schema for Parquet. It must be specified manually.; 阅读详情

Variable argument lists in Cocoa

This week I'll talk about methods that take variable numbers of arguments, also known as variadic methods. I'll show you the Objective-C syntax and implementation, give a quick rundown of the ways that Cocoa classes provide variable argument support and I'll also show you a way to fake va_list parameters to handle Cocoa's variadic method equivalents at runtime.

Variable arguments basics

Passing a variable number of arguments to a method is a convenient way to handle a list of variables that are in scope at compile time.

The Objective-C language handles variable arguments in the same way that Standard C does. Normally, you will encounter variable argument lists in one of two forms: "Format strings" or "Nil terminated lists".

Format strings

The traditional example for variable arguments are format strings. Format strings contain a number of "placeholders" (escape sequences starting with a "%" sign) that are replaced with data from variables when the format string and the variable arguments are passed to the method.

NSString *myString = [ NSString stringWithFormat :
     @"Number %d, String: %@, Float: %g" , 1 2 3 , @"SomeString" , 3 4 .5 ];

This method is declared as follows:

+ ( id )stringWithFormat:( NSString *)format, ...;

The "..." is the variable argument.

This method declares a first parameter but everything else is "variable". This does not mean optional. Instead, it means that a number of extra parameters will be required. Exactly what number and their types depends on how the method works.

The documented behavior for stringWithFormat:, is that it scans the format string and requires 1 variable argument for every escape sequence (in this case there are 3) and the type must match the specifier for each escape sequence (in this case, "d", "@" and "g" specify int, id and float/double).

Nil terminated lists

The other common type of variable argument list method is one that takes a list of objects terminated by nil.

In Cocoa, these are commonly used for constructing collection objects.

NSArray *myArray = [ NSArray arrayWithObjects : @"One" , @"Two" , @"Three" , nil ];

The documented rule for this type of method is that the last argument must be nil.

Getting argument numbers wrong

The details of "Format strings" and "Nil terminated lists" reveal the difficulty with variable argument lists in Objective-C: knowing how many arguments exist — i.e. when to stop reading arguments.

Objective-C, like C, does not have a runtime argument count, nor does it pass runtime argument types. So the number and types of arguments must be determined by some other policy. In the case of these two examples, the argument count is, respectively: the number of escape sequences in the "Format string" or the number of arguments before the first nil. For "format strings" the types are determined by the escape sequences, for "Nil terminated" lists, the arguments are always pointers.

The penalty for getting variable argument list wrong can be severe: the compiler won't typically notice a problem and your code will crash or behave very strangely at runtime. The important lesson to learn is that you should only use variable arguments in a situation where the policy for numbers and types of arguments is very clear.

You can improve the compiler verification of variable argument lists by using the -Wformat compiler flag in GCC. See below for more about how this works.
Implementing variable arguments for your own methods

Lets look at the implementation for the example class:

@interface StringContainer : NSObject
{
     NSString *contents;
}
@end

Imagine we wanted a method that would set the contents string this class contains by concatenating a variable argument list of strings together.

In this case, we will use the nil terminated approach — the list of strings to concatenate will end with a nil, so we know when to stop reading.

The declaration for the method looks like this:

- ( void )setContentByAppendingStrings:( NSString *)firstString, ...
     NS_REQUIRES_NIL_TERMINATION ;

The NS_REQUIRES_NIL_TERMINATION part is a macro that tells the compiler that invocations of this method must include a nil-terminated list of arguments. Failure to nil-terminate the list will result in a compiler warning if -Wformat is enabled.

Annoyingly, -Wformat is not enabled by default. Double annoyingly, it is named "Typecheck Calls to printf/scanf" in the "GCC 4.0 Warnings" section of the "Build Settings" in Xcode, even though this setting affects the NS_REQUIRES_NIL_TERMINATION macro which is used commonly throughout all of Cocoa — far beyond printf and scanf.

The implementation of this method is as follows:

- ( void )setContentByAppendingStrings:( NSString *)firstArg, ...
{
     NSMutableString *newContentString = [ NSMutableString string ];
     va_list args;
     va_start(args, firstArg);
     for ( NSString *arg = firstArg; arg != nil ; arg = va_arg(args, NSString*))
     {
         [newContentString appendString :arg];
     }
     va_end(args);
     
     [contents autorelease ];
     contents = [newContentString retain ];
}

The va_list, va_start, va_arg and va_end are all standard C syntax for handling variable arguments. To describe them simply:

  • va_list - A pointer to a list of variable arguments.
  • va_start - Initializes a va_list to point to the first argument after the argument specified.
  • va_arg - Fetches the next argument out of the list. You must specify the type of the argument (so that va_arg knows how many bytes to extract).
  • va_end - Releases any memory held by the va_list data structure.

Generally speaking, you can use this for loop for any variable argument situation where your arguments are all the same type. Other cases are a bit trickier but far less common — I'm sure you can work out how they would work if needed.

va_list in Cocoa

A number of classes in Cocoa have methods that take variable numbers of arguments. In most cases, these classes will also have an equivalent method that takes a va_list.

We can see an example of these va_list equivalents by looking at NSString. NSString declares the class method stringWithFormat:... (which takes a variable number of arguments) and NSString also declares the instance method initWithFormat:arguments: (where the arguments parameter is a va_list) which handles the equivalent behavior of stringWithFormat:....

These va_list methods are used in the situation where your class defines a method with a variable argument list and you need to pass those variable arguments into the Cocoa method. For example, if the StringContainer class listed above declared the method:

- ( void )setContentsWithFormat:( NSString *)formatString, ...;

The implementation of this method would be as follows:

- ( void )setContentsWithFormat:( NSString *)formatString, ...
{
     [contents autorelease ];
 
     va_list args;
     va_start(args, formatString);
     contents = [[ NSString alloc ] initWithFormat :formatString arguments :args];
     va_end(args);
}

The va_list parameter allows us to pass our own variable argument list to the Cocoa method so that the Cocoa method can handle the arguments.

Creating a fake va_list

The va_list methods in Cocoa are helpful if you actually have a variable argument list.

There is another situation you many encounter though: you want to use a method like -[NSString initWithFormat:arguments:] using a runtime generated array of arguments. There is no NSString format method that takes an NSArray of arguments, so how could we handle a format string at runtime?

The answer lies in how va_list works. While GCC makes it very clear that va_list is "platform specific", the reality is that on Mac and iPhone Objective-C platforms, it is simply a byte buffer containing the arguments. In fact, if you've ever used an ABI inspection tool (like class-dump-x) on a method taking a variable argument list, you'll see that it is simply a char *.

To show how we can use this knowledge, consider the following method on the StringContainer class:

- ( void )setContentsWithFormat:( NSString *)formatString arguments :( NSArray *)arguments;

If we assume that all of the variable arguments required fro the formatString are objects, then we can implement this method as follows:

- ( void )setContentsWithFormat:( NSString *)formatString arguments :( NSArray *)arguments
{
     [contents autorelease ];
 
     char *argList = ( char *)malloc(sizeof( NSString *) * [arguments count ]);
     [arguments getObjects :( id *)argList];
     
     contents = [[ NSString alloc ] initWithFormat :formatString arguments :argList];
     
     free(argList);
}

What I've done here is simply copied the NSArray to a C-style byte buffer and then passed that buffer to the initWithFormat:arguments: method.

If your arguments are not all Objective-C objects, you'd need to take greater care to assemble the byte buffer but the principles would be the same.

Some variadic notes
NSInvcation incompatibility

NSInvocation does not support variadic methods. I'm not sure why this is — maybe NSInvocation wants to avoid making assumptions about va_list, maybe it is because NSMethodSignature can't describe the storage requirements of variable arguments for NSInvocation or maybe the Cocoa developers have families and just wanted to go home early.

Variadic macros

You can also write variadic macros, much like variadic methods, by using the ##__VA_ARGS__ placeholder in your macros. See the macros near the bottom of my post titled Supersequent Implementation for an example of how this works. As discussed briefly in that article, the version of GCC used for iPhone development handles variadic macros slightly differently, so pay attention to the differences when targetting the iPhone platform.

Conclusion

Variadic methods require a degree more care than regular methods because variable argument lists have no "introspection" (you cannot ask for the number and type of arguments) — so their usage relies on documentation and implicit agreements between the sender and receiver.

In your own code, variadic methods should be used sparingly — passing variables in an NSArray or NSDictionary is safer (if slightly slower and syntactically more verbose) due to the fact that these classes do offer introspection.

When the implicit sender/receiver agreement is clear, variadic methods work well. They certainly make creating instances of NSArray, NSSet, NSDictionary easier and they are the only way to create a formatted NSString in a single invocation.

Variable-length Argument Lists 立即下载

相关推荐

【深度学习预测】项目介绍 Python实现基于BO-Transformer-LSTM贝叶斯优化算法(BO)优化Transformer-LSTM模型进行多变量时间序列预测(含模型描述及部分示例代码)

内容概要:本文详细介绍了一个基于BO-Transformer-LSTM的多变量时间序列预测项目,通过结合Transformer的全局自注意力机制与LSTM的局部时序建模能力,构建了适用于复杂业务场景的深度学习预测模型。模型输入采用多变量滑动窗口结构,并引入正弦余弦位置编码以保留时间顺序信息;Transformer编码器提取变量间长距离依赖关系,LSTM进一步捕捉动态演化特征,最终通过回归层输出预测值。为优化模型性能,采用贝叶斯优化算法(基于Tree-structured Parzen Estimator)自动搜索最优超参数组合,包括嵌入维度、注意力头数、学习率、窗口长度等,显著提升了调参效率与模型泛化能力。项目还设计了包含周期性、趋势性、均值回归、突发事件和异方差噪声的五因素模拟数据生成机制,确保数据贴近真实业务场景,并建立了从数据预处理、模型训练、验证评估到结果恢复的完整技术链路。; 适合人群:具备一定机器学习与深度学习基础,熟悉PyTorch框架,从事时间序列预测相关研究或工程应用的研发人员、数据科学家及研究生。; 使用场景及目标:①应用于能源负荷预测、设备状态监测、金融风控、供应链需求预测等多变量时间序列预测任务;②解决传统模型在长时依赖、非线性关系和高维特征下的预测瓶颈;③实现高效超参数优化,提升模型调优自动化水平与部署可行性。; 阅读建议:本文含核心模型结构与部分示例代码,建议结合完整项目代码(如GitHub或博客资源)进行复现实践,重点关注数据生成逻辑、模型前向传播流程及贝叶斯优化集成方式,同时可通过调整网络结构或优化策略进一步拓展至多步预测、概率输出与可视化分析等高级功能。

解决SparkSql 读取parquet或者Orc文件报错Unable to infer schema for Parquet. It must be specified manually

val conf = new SparkConf().setAppName(getClass.getSimpleName).setMaster("local[4]") val spark = SparkSession.builder().config(conf).getOrCreate() val sc = spark.sqlContext val path="/data_file/tp=acc...

qq_40625030的博客 2万+

城市生命线之长距离输水管线的监测与检测.pdf

城市生命线之长距离输水管线的监测与检测.pdf

可变长的参数列表(variable-length argument lists)

  可变长参数列表,也叫“varargs”,它允许方法在调用的时候接受任意数目个参数,比如常见的printf()式的打印方式即允许在一个字符串中嵌入多个标签、并且每个标签接收一个参数。   声明“varargs”的方法是:在应该使用的数组方括号的位置,使用省略号(...),例如: void printfObjects ( Object ... list ) {     //list is ...

common_heart的博客 1205

能带图详解:价带、导带、禁带与带隙Eg决定半导体光学特性

在半导体物理与光电工程中,能带结构是理解材料电学和光学性质的基础。孤立原子的电子能级在晶体中展宽形成能带,其中价带是电子常驻区,导带是电子跃迁后的自由移动区,而禁带(带隙Eg)则是电子无法存在的能量间隔。带隙大小直接决定了材料是导体、半导体还是绝缘体,并制约着光吸收边、发光波长和探测响应范围。通过公式λ=1240/Eg,可从带隙快速估算材料对光的吸收与发射特性,这对LED、太阳能电池、光电探测器等器件的选型与设计至关重要。本文以图解方式系统梳理能带图的坐标含义、直接/间接带隙的区别,以及利用带隙估算器件光谱

weixin_30536861的博客 328

【XR硬件介绍】PICO Space Pro(Project Swan)深度解析:字节 2026 旗舰 MR 头显延期背后

内部代号 Project Swan 的 PICO 年度旗舰 MR 头显正式定名PICO Space Pro,原本计划 2026 年 9 月对外发布,官方官宣推迟至 2026 年第四季度上市。硬件层面已经完成 FCC 认证,硬件成熟度较高,延期核心目标是打磨 PICO OS 6 空间操作系统,补齐空间计算软件能力。本文从产品背景、硬件架构、软件生态、延期逻辑、行业竞争格局几个维度拆解这款国产高端 MR 设备,分析它对国内 XR 产业的意义与待解的问题。

houdou112358的博客 1365

variable-length argument lists

The best example of variable-length argument lists function is printf() the proper declaration for printf() is                                                               int printf(char * format,

oliveevilo的专栏 910

三角洲行动交易行自动化脚本

DFMarketBot - 三角洲行动自动交易助手 DFMarketBot是一款专为三角洲行动游戏设计的交易行自动化工具,通过OCR识别和鼠标模拟实现自动补卡、补子弹功能。项目采用Python开发,支持Windows平台,主要功能包括: 自动检测并购买指定物品(房卡/子弹) 价格监控与智能购买(低于设定价格自动下单) 自定义购买数量与次数限制 支持窗口/无窗口两种游戏模式 使用前需安装Tesseract OCR引擎并配置游戏为1920*1080分辨率。通过JSON文件可灵活配置监控物品清单、理想价格和购买策

愤怒的阿木木的博客 3万+

报错Attribute "path" is required and must be specified for element type

Attribute “path” is required and must be specified for element type,最近搞一个项目总遇到这个或者类似的问题,其实问题很简单。其实就是batis和MyBatis之间有区别,就是在Batis里面mapping配置文件,你会看到一些元素“XXXClass”或者“Class”。但是在MyBatis里面很多却改成了“XXXType”和“Ty...

FeiChangWuRao的博客 6222

PY32F406K1CU6 FLASH模拟EEPROM

摘要:本文介绍了基于STM32 FLASH模拟EEPROM的实现方法。头文件flash.h定义了FLASH页大小(256字节)、用户存储区域(4页)及地址范围,提供了等待周期配置和地址校验宏,声明了EEPROM初始化、读写操作等函数接口。源文件flash.c实现了具体功能:配置FLASH等待周期(144MHz需3WS)、页读写擦除操作,以及EEPROM初始化(解锁-擦除-验证-锁定)和缓冲区读写功能。其中写操作采用"读页→更新→擦除→编程"的流程,确保数据安全写入。该方案适用于需要非易失

sam的博客 199

大模型系列——Ollama简明教程

在这篇文章中,我们将了解如何使用 Ollama、如何在 Ollama 中创建自己的模型 以及如何使用 Ollama 构建聊天机器人。这是深入研究 Ollama 的第一部分,以及我所学到的有关本地 LLM 的知识以及如何将它们用于基于推理的应用程序。在这篇文章中,你将了解——

2401_84052244的博客 1万+

函数变参(Variable arguments)

//首先说明问题://      所谓函数变参指的是在编译时无法确定该函数在调用时参数列表中参数的类型和数量,比如大名鼎鼎的“print”系列;  一、99C标中函数变参的实现:      总体上说就是一个类型外加四个宏函数,这都在stdarg.h里有定义。      (1)、类型va_list:使用时首先用va_list定义一个变量用于保存某个变参函数某次变参使用相   

Foru 585

Windows Server 安装 AD 域服务一直失败?一招搞定“请求添加或删除指定服务器上的功能失败”

这个问题看似简单,其实暗藏了几个“隐藏门槛”,像是服务未开启、端口未开放、网卡组件未勾选、虚拟机 SID 冲突等等,尤其在云上装 AD 更容易踩坑。建议每一步都排查一下,尤其是服务和防火墙,很多安装失败其实都是被这两处给卡住了。如果你也遇到 “请求添加或删除指定服务器上的功能失败”,不妨参考这篇文章挨个试试看,说不定就能解决问题!

代码简单说 Vue、JAVA、PHP、Node.js 熟练运用,接口、架构、性能全搞定。 1444

关于eclipse的启动问题

包括英文版本和中文版本两种的说明, 特别需要值得一提的是那个 -nl 参数, 可以指定程序启动时所使用的语言. 例如:eclipse -nl en_US将启动英文语言, 这个特性在安装了国际化语言包以后特别有用, 可以方便的切换各个语言的版本. 注意 IBM WSAD v5.1 也支持这个功能.运行 Eclipse将 Eclipse 驱动程序安装(解压缩)到某个目录(例如,c:/eclip

狗 2438

蓝牙协议栈详解(3)——BTstack

BTstack是一个轻量级蓝牙协议栈,支持经典蓝牙(BR/EDR)和低功耗蓝牙(BLE)。它采用事件驱动模型,可运行在MCU/CPU上,通过HCI接口与蓝牙控制器通信。协议栈包含完整的蓝牙协议层支持,如L2CAP、RFCOMM、ATT/GATT等,并提供丰富的示例代码。 主要特点包括模块化设计、开源授权、支持多种HCI传输方式(UART/USB)和操作系统适配。开发时需要关注事件驱动编程模型、内存配置优化、HCI传输稳定性等问题。典型应用场景包括SPP串口通信、BLE外设开发等。 使用建议从最小示例开始,逐

嵌入式软硬件叶玄 304

DAB协议解读ETSI TS 103 461

数字信号广播( Digital Audio Broadcasting 简称DAB)是继AM、FM传统模拟广播之后的第三代广播--数字信号广播,它提供了接近CD质量的声音,广播及商机无限的附加数据服务,具有抗噪声、抗干扰、抗电波传播衰落、适合高速移动接收等优点,保证固定、携带及移动时接收信号的质量。DAB的原始版本使用MP2音频编解码器。该系统的升级版本于2007年2月发布,称为DAB+,它使用基于改进的离散余弦变换(MDCT)的HE-AACv2(AAC+)音频编解码器。

qflook的博客 4494

android开发时,finish()跟System.exit(0)的区别

finish是Activity的类,仅仅针对Activity,当调用finish()时,只是将活动推向后台,并没有立即释放内存,活动的资源并没有被清理;当调用System.exit(0)时,杀死了整个进程,这时候活动所占的资源也会被释放

影儿的专栏 1895

大中型超市收银系统(可直接运行)

光步前台收银系统系统功能:商品销售、商品退货、挂单、收银员权限、会员销售、单品取消、整单取消、商品查询、脱机销售、脱机数据上传,基本资料下载,开钱箱、小票打印、收款结算,支持多币种付款方式(现金、储值卡、礼券、微信等),支持多种促销。运行环境:.net 4.0登陆信息用户名:1001 密码:123456内置商品信息,商品编码可输入00001000 - 00010000,测试效果相关功能键F5 结算 F9挂单 F11商品查询 F8退货 Insert单品取消 Del整单取消 F12开钱箱F2 会员 Ctrl+Z退出系统 Home 锁屏 相关源码待公开

Mybatis报TypeException:JDBC requires that the JdbcType must be specified for all nullable parameters.

查看打印出来的sql是否有错。 如何没有错误就去查看对应的XXXDao.xml文件,查看文件内的语句(注意的是判断的部分) 这好像是sql语句有错才报出

千尘梦博客 1万+

IEM模型,地表粗糙度模拟

利用微波反演土壤水分时候,利用IEM模型可以实现对随机地表的模拟

IMSL CNL 7.0.0 (x86-64)Crack

IMSL CNL 7.0.0 (x86-64)Crack intel的算法库破解文件,这是C++版本的破解文件

hive小操作·关于 spark2.4-读取hive3.1事务表

版本信息: spark2.4 hive3.1.1 异常情况: 使用 alter table * compact 'major'后,spark仍无法读取hive事务表中数据 具体流程如下 1、建表语句 create table sugon_transaction(id Int,name String) clustered by (name) into 3 buckets stored ...

concealed0的博客 5431

锂电池充电器电路设计 里面有电路

锂电池充电器电路设计 里面有电路 3.7V升压到5V电路设计。

parquet列式文件实战(未完,待续)

parquet列式文件实战 parquet code demo http://www.programcreek.com/java-api-examples/index.php?source_dir=hiped2-master/src/main/java/hip/ch3/parquet/ExampleParquetMapReduce.java 开源列式存储引擎Parqu...

weixin_30859423的博客 149

variable argument list

variable argument:#define _ADDRESSOF(v)   ( &reinterpret_cast(v) )#elif   defined(_M_IX86)//Interge promotions#define _INTSIZEOF(n)   ( (sizeof(n) + sizeof(int) - 1) & ~(sizeof(int) - 1) )//v

feixie1225的专栏 1077

Mybaties-foreach 遇到mybatis 异常: JDBC requires that the JdbcType must be specified for all nullable pa

项目上遇到了mybatis 异常: JDBC requires that the JdbcType must be specified for all nullable parameters.1.此种情况 由于 mybatis 映射文件中,sql 参数值为 null , 由于 还有另一种 关于 参数为 null 的出现 oracle 无效列类型错误  1111 的异常,那种情况 发现 写的参数 是...

qq_29178991的博客 980

Warning: Invalid argument supplied for foreach() in 的解决方法

在php中,foreach遍历数组如果不是一个有效数组,php会报一个错误警告 “Warning: Invalid argument supplied for foreach() in ……” ,很多时候这个数组是取自某些数据源,如果数组为空,就会出现错误警告,为了防止这种错误警告,应该在遍历之前对数组变量进行一个判断,如果该变量不是一个有效数组,可以对该变量加个if判断语句,还可以设置该

3万+

n个数字连乘的计算(Variable-Length Argument List)

程序功能: n个数字的连乘结果=N1*N2*N3*...*Nn,n的大小由用户输入时随意控制,所支持的最大连乘次数则在程序中通过final值设定(暂定为100,够长了吧)。   代码如下: package example; //JHTP Exercise 7.14: Variable-Length Argument List //by pandenghuang@163.com /**(V...

预见未来to50的专栏 3229
上一篇: va_list & va_start & va_arg & va_end
下一篇: [问题]duplicate symbols for architecture armv7
skyming
博客等级 码龄15年 249粉丝 175原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值
⌂ 换网址