tags:

views:

75

answers:

3

can someone clarify this for me:

When there’s more than one argument, the arguments are declared within the method name after the colons. Arguments break the name apart in the declaration, just as in a message. For example:

- (void)setWidth:(float)width height:(float)height;

So in the above:

  1. method is for instance variables
  2. returns void
  3. parameter#1 is a float, named width.

  4. parameter#2 is a float,named height.

But why is it hieght:(float)height; and not just:

- (void)setWidth: (float)width (float)height;
+1  A: 

That's just a feature of Objective-C to make your life easier when reading the method invocation, which would look like:

[myObject setWidth:w height:h];

You can leave the labels out (except the first one), so if you really want to, you can have:

-(void)setWidth:(float)width :(float)height
{
  ...
}

and use it as:

[myObject setWidth:w :h];

But that's not really in the spirit of the Objective-C language. The entire point of those labels is to make those calls easier to understand without having to look up the method definition.

Carl Norum
Objective-C does *not* have "labeled" arguments. You can't just leave out part of a method name. That is, in the above example the method 'setWidth::' is a different method from 'setWidth:height:' (this often confuses new folk).
bbum
@bbum, yes absolutely. I didn't mean to create any impression that they are the same. Do you have a suggestion for how I can clarify that?
Carl Norum
I haven't come up with a terribly good description beyond "Objective-C interleaves the method names with the arguments to improve readability and descriptiveness within code.".
bbum
+1  A: 

The fact that the argument name happens to also be in the method name is confusing you. Think about how you actually call it:

[something setWidth:500 height:250];

Following your suggestion, it would be something like this instead:

[something setWidth:500 250]; // That 250 is just kind of hanging 
                              // out there — not very readable

You could also give the argument a totally different name from the part of the method name that precedes it:

- (void)setGivenName:(NSString *)first surname:(NSString *)last
Chuck
just confusing, in c# it would be:void SetWidth(int width, int height);object.SetWidth(500, 200);there seems to be something a bit strange, all parameters don't seem to be the same convention.
Blankman
+6  A: 

Objective-C does not have named arguments. Nor does it have "keyword arguments".

Objective-C uses what is called "interleaved arguments". That is, the name of the method is interleaved with the arguments so as to produce more descriptive and readable code.

[myObject setWidth:w height:h];

The above reads, effectively, as tell myObject to set the width to w and height to h.

In the above case, the method's name -- its selector -- is exactly setWidth:height:. No more, no less.

This is all explained in the Objective-C guide.

bbum