Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do objective-c array parameters not use colon notation?

Tags:

objective-c

Im currently learning some objective-c from the big ranch guide book. My understanding is that methods with multiple parameters use colons to separate each parameter, but when reading about creating arrays, i found this snippet of code:

 NSArray *dateList = [NSArray arrayWithObjects:now, tomorrow, yesterday, nil];

This has left me confused as i thought objective-c method parameters must each be preceded by a portion of the method name along with a colon. Can anybody explain this to me?

like image 272
Dom Shahbazi Avatar asked Dec 24 '22 18:12

Dom Shahbazi


2 Answers

This is an exception to the rule; this is commonly called a variadic method. If you look at the definition in NSArray.h:

+ (instancetype)arrayWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;

you see that you can specify an arbitrary number of parameters, as long as the last one is nil (this is called the sentinel).

This saves the developers from creating a large number of different methods having roughly the same functionality, each of which accept a different number of parameters. They did so in NSObject, where you have

- (id)performSelector:(SEL)aSelector withObject:(id)object1;
- (id)performSelector:(SEL)aSelector withObject:(id)object1 withObject:(id)object2;

(but no further methods).

like image 105
Glorfindel Avatar answered Dec 28 '22 08:12

Glorfindel


The method only has one parameter, a variable parameter list.

Here is the Objective-C declaration from the Apple Developer website:

+ (instancetype nonnull)arrayWithObjects:(ObjectType nonnull)firstObj, ...;

There's no need for colon separation, because the object list is treated as one parameter, even thought it looks like many parameters!

like image 41
djones Avatar answered Dec 28 '22 09:12

djones