Why do argument lists in certain Cocoa methods end with a nil?

好久不见. 提交于 2019-11-28 01:57:15

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.

Variadic functions in Objective-C don't have a way of determining when your argument list ends, other than providing a nil argument.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!