为什么NSArray arrayWithObjects需要终止nil? [英] Why does NSArray arrayWithObjects require a terminating nil?

查看:76
本文介绍了为什么NSArray arrayWithObjects需要终止nil?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道它标志着一组可变参数的结束,但是为什么不能以不需要nil的方式实现它呢?

I understand that it marks the end of a set of varargs, but why can't it be implemented in such a way that doesn't require the nil?

推荐答案

这都与C调用ABI有关.

It all has to do with the C calling ABI.

考虑以下方法:

- (id)initWithFormat:(NSString *)format, ...;
+ (id)arrayWithObjects:(id)firstObj, ...;
+ (id)dictionaryWithObjectsAndKeys:(id)firstObject, ...;

...告诉编译器可能存在可变数量的任何类型的参数.编译器无法知道这些类型必须是什么(实际定义中有有助于此的标记).

The ... tells the compiler that a variable number of arguments of any type may be present. There is no way for the compiler to know what those types are required to be (the real definitions have markers that help with that).

现在,考虑三种方法.对于变量自变量列表中可能出现的内容,这三个方面都有很大不同的要求.数组必须是一堆对象,后跟一个nil.字典需要一堆对象,然后是nil.最后,string方法需要一堆与格式字符串中的类型匹配的参数.

Now, consider the three methods. All three have vastly different requirements for what might be present in the variable argument list. An array must be a bunch of objects followed by a nil. The dictionary requires a bunch of pairs of objects followed by a nil. Finally, the string method requires a bunch of arguments that match the types in the format string.

所有这些行为都直接与所调用的方法相关,并且,如果API的作者决定采用难于使用"的方法,则可以在运行时修改解码可变参数的行为,以维持生命困难.

All of these behaviors are directly tied to the method being invoked and, if the author of an API decided to go for "hard to use", the behavior of decoding the variable arguments could be modified at runtime, just to make life difficult.

底线:C ABI没有允许指定方法或函数采用可变数量的参数的语法,这些参数或参数对参数或其终止具有任何类型的约束.

Bottom line: The C ABI doesn't have a syntax that allows for specifying that a method or function takes a variable number of arguments with any kind of set of constraints on the arguments or their termination.

Objective-C可以更改仅用于方法声明&的规则.调用,但这对C函数或C ++毫无帮助,而这两个函数必须与Objective-C保持兼容.

Objective-C could change the rules just for method declarations & invocations, but that wouldn't help with C functions or C++, both of which Objective-C must remain compatible with.

这篇关于为什么NSArray arrayWithObjects需要终止nil?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆