今天讲Objective-C的方法参数,Objective-C的方法参数和其它大多数高级语言的有很大不同,那Objective-C的方法参数有什么特别的呢?
Methods Can Take Parameters
If you need to declare a method to take one or more parameters, the syntax is very different to a typical C function.
For a C function, the parameters are specified inside parentheses, like this:
void SomeFunction(SomeType value);
An Objective-C method declaration includes the parameters as part of its name, using colons, like this:
- (void)someMethodWithValue:(SomeType)value;
As with the return type, the parameter type is specified in parentheses, just like a standard C type-cast.
If you need to supply multiple parameters, the syntax is again quite different from C. Multiple parameters to a C function are specified inside the parentheses, separated by commas; in Objective-C, the declaration for a method taking two parameters looks like this:
- (void)someMethodWithFirstValue:(SomeType)value1 secondValue:(AnotherType)value2;
In this example, value1 and value2 are the names used in the implementation to access the values supplied when the method is called, as if they were variables.
Some programming languages allow function definitions with so-called named arguments; it’s important to note that this is not the case in Objective-C. The order of the parameters in a method call must match the method declaration, and in fact the secondValue: portion of the method declaration is part of the name of the method:
someMethodWithFirstValue:secondValue:
This is one of the features that helps make Objective-C such a readable language, because the values passed by a method call are specified inline, next to the relevant portion of the method name, as described in You Can Pass Objects for Method
Parameters.
Note: The value1 and value2 value names used above aren’t strictly part of the method declaration, which means it’s not necessary to use exactly the same value names in the declaration as you do in the implementation. The only requirement is
that the signature matches, which means you must keep the name of the method as well as the parameter and return types exactly the same.
As an example, this method has the same signature as the one shown above:
- (void)someMethodWithFirstValue:(SomeType)info1 secondValue:(AnotherType)info2;
These methods have different signatures to the one above:
- (void)someMethodWithFirstValue:(SomeType)info1 anotherValue:(AnotherType)info2;
- (void)someMethodWithFirstValue:(SomeType)info1 secondValue:(YetAnotherType)info2;