Why does NSArray arrayWithObjects require a terminating nil?

前端 未结 6 831
时光取名叫无心
时光取名叫无心 2020-12-03 01:29

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?

6条回答
  •  -上瘾入骨i
    2020-12-03 02:34

    There are various workarounds, but my current favorite is good for apps more than for released frameworks. Accept an NSArray in your method instead of "...", and then fill it with the convenience macro below, which is placed in your prefix file or utility header.

    #define $array(objs...) [NSArray arrayWithObjects: objs, nil]

    It'll allow for multiple well labeled variable length arguments and you'll free yourself from the archaic pattern of having to use the first argument and then va_list and its brothers in favor of a for-in loop or the many other collection tools available.

    [self findMatchingSetAndAlert:@"title" ties:$array(tie1, tie2, tie3) shirts:$array(shirt1, shirt2, shirt3, shirt4)];

    If someone knows how to implement a non-nil-delimited list such as stringWithFormat, please let us know! It uses attributes and macros or something designed specifically for formatting, but those are implemented somehow.

提交回复
热议问题