Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Objective-C method signatures. Are they inconsistent?

Tags:

objective-c

I'm new to Objective-C, but please help me out here.

What I'm seeing is that method signatures in Objective-C that take multiple parameters seem inconsistent.

Example:

- (void) sendEmail: (NSString *) toStr
         subject:(NSString *) subjectStr
         body:(NSString *) bodyStr;

OK, so here we have 3 "parameters" (at least that's what I'm used to calling them), but 2 of them have "external" names (subject, body) but the first one doesn't! Isn't there something wrong with that from a consistency/style point of view?

When we call this method we do it like:

[emailObj sendEmail:@"[email protected]" subject:@"testSub" body:@"this is a test"]

(Hopefully I did that right, remember I'm new to this.)

So the subject and the body are clearly marked in the call, but not the "to" address? It seems really wacked to me. Why is that first parameter getting special treatment?

like image 674
Fraggle Avatar asked Oct 11 '10 15:10

Fraggle


3 Answers

I guess you thought that in the method declaration

-(void) A:(NSObject*)a B:(NSObject*)b C:(NSObject*)c

A is the method name, B and C are the names of parameters.

In Objective-C, the totality A:B:C: is the method name (more technically, called the selector) and used as a unit when you call a method by name. For example,

 if([obj respondsToSelector:@selector(A:B:C:)]){
     ...
 }

checks if obj responds to A:B:C:. But [obj respondsToSelector:@selector(A:)] will be NO in this case.

So, you should really think of the totality of A:B:C: as the method name, and A is the name of the first parameter.

Note also that you can't call A:B:C: as A:C:B:, either.

like image 159
Yuji Avatar answered Oct 16 '22 04:10

Yuji


In most cases, methods like this are normally named so that the lack of a name on the first parameter makes sense. In this case, I would expect something like sendEmailTo.

like image 12
Adam Robinson Avatar answered Oct 16 '22 05:10

Adam Robinson


I would say that if you're confused about what a method does, then it's probably not named as well as it could've been.

Given the selector above, I would expect the 3 parameters to be some sort of email object, a subject, and a body. Since, however, the first parameter is not an "Email" object but rather the recipient of an email, I would probably rename this method to be:

- (void) sendEmailToRecipient:(NSString *)recipient subject:(NSString *)subject body:(NSString *)body;
like image 10
Dave DeLong Avatar answered Oct 16 '22 04:10

Dave DeLong