Don't understand multiple parameter declaratio

2020-06-21 06:32发布

问题:

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:

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.



回答2:

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.



回答3:

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


标签: objective-c