Let's say we're going to declare a method for a class Alien that moves the alien to a new position on the screen. The method declaration might look like this:
-(int) moveToX: (int) newX Y: (int) newY;
The hyphen indicates this is an instance method. The (int) indicates the method returns an integer (maybe some kind of status code indicating whether or not the move was successful). So far, so good. Now for the trick question: what's the name of the method? It's not "moveToX"; it's "moveToX:Y:". Huh?
The method declared above takes two arguments, the values of which can accessed from within the method using variables newX and newY. Both arguments are integers. Objective C provides for the labeling of method arguments, but it does it in a way that mingles what would normally be thought of as the method name ("moveTo") and the label of the first argument ("X"). The labels of subsequent arguments (like "Y") stand alone.
Argument labeling in method declarations is not required. What is required is a word followed by a list of colon-prefixed argument declarations. For example, here's a more minimalist declaration of the same method:
-(int) moveTo: (int) newX : (int) newY;
The two methods are functionally identical, but the official name of the second method is "moveTo::". This style of syntax, while slightly odd to someone coming from a Java or C++ background, is more consistent with the method-name-then-argument-list approach seen in many other languages.
While this second approach may seem less confusing, it is apparently frowned upon. Consider the syntax for calling this second method:
int n = [myAlien moveTo:10 :30];
This code creates integer variable n, calls the moveTo:: method of the myAlien object with the arguments 10 and 30, and places the result of the method call in n. By itself, this line of code doesn't provide many clues about what the values 10 and 30 are expected to represent. Consider instead a call to the moveToX:Y: method:
int n = [myAlien moveToX: 10 Y: 30];
Here, it's much more apparent what's expected of the provided arguments, thus the code is -- at least in principle -- more readable.
It's important to note, however, that Objective C's support for argument labeling ends here. Method calls must use the full method name. This means that, unlike with argument naming support in some other languages, all method argument labels used in the declaration must appear in the method call, and in the correct order.
References:

No comments:
Post a Comment