Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
368 views
in Technique[技术] by (71.8m points)

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

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];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...