为什么在某些Cocoa方法中的参数列表以nil结尾? [英] Why do argument lists in certain Cocoa methods end with a nil?

查看:261
本文介绍了为什么在某些Cocoa方法中的参数列表以nil结尾?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么一些方法中的参数列表以 nil 结尾?我特别在集合类中注意到了这一点,例如 NSSet

  mySet = [NSSet setWithObjects:someData,aValue,aString,nil]; 

NSArray

  NSArray * objects = [NSArray arrayWithObjects:@value1,@value2,@value3,nil]; 


解决方案

它与变量参数列表的工作方式 va_list ,在参数中显示为 ... )。当代码试图提取列表中的所有值时,它需要知道什么时候停止(因为它不知道有多少)。我们用名为sentinel的特殊值表示列表的结尾,通常为 NULL 。这样,当处理代码在 va_list 中遇到 nil 时,它知道它已到达结束。如果你省略了 nil ,你会得到奇怪的错误,因为代码只是继续读下堆栈,解释为对象,直到找到一个 nil



这非常类似为什么C字符串必须 NULL -terminated。



注意, stringWithFormat:和类似 printf -style方法不需要一个sentinel,因为它根据多少修饰符的格式来确定它需要多少参数串。因此,如果你给一个格式字符串 @hello,%@,那么它只会寻找一个额外的参数,因为只有一个%修饰符。 >

Why do argument list in some methods end with nil? I have noticed this particularly in the collection classes, for example NSSet:

mySet = [NSSet setWithObjects:someData, aValue, aString, nil];

and NSArray:

NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", @"value3", nil];

解决方案

It has to do with how variable argument lists work (va_list, seen as ... in the parameters). When the code is trying to extract all of the values in the list, it needs to know when to stop (because it doesn't know how many there are). We denote the end of the list with a special value called a "sentinel", which is usually NULL. That way, when the processing code comes across a nil in the va_list, it knows that it's reached the end. If you leave out the nil, you'll get strange errors, because the code will just keep on reading down the stack, interpreting things as objects, until it finds a nil.

This is very similar to why C strings have to be NULL-terminated.

As a side note, the stringWithFormat: and similar printf-style methods don't need a sentinel, because it figures out how many parameters it needs based on how many % modifiers are in the format string. So if you give a format string of @"hello, %@", then it will only look for one extra argument, because there is only one % modifier.

这篇关于为什么在某些Cocoa方法中的参数列表以nil结尾?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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