Methods with multiple arguments in objective C

前端 未结 3 736
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-29 12:46

If you take this method call for instance(from other post)

- (int)methodName:(int)arg1 withArg2:(int)arg2
{
    // Do something crazy!
    return someInt;
}
         


        
3条回答
  •  死守一世寂寞
    2021-01-29 13:42

    As Tamás points out, withArg2 is part of the method name. If you write a function with the exact same name in C, it will look like this:

    int methodNamewithArg2(int arg1, int arg2)
    {
      // Do something crazy!
      return someInt;
    }
    

    Coming from other programming languages, the Objective-C syntax at first might appear weird, but after a while you will start to understand how it makes your whole code more expressive. If you see the following C++ function call:

    anObject.subString("foobar", 2, 3, true);
    

    and compare it to a similar Objective-C method invocation

    [anObject subString:"foobar" startingAtCharacter:2 numberOfCharacters:3 makeResultUpperCase:YES];
    

    it should become clear what I mean. The example may be contrived, but the point is to show that embedding the meaning of the next parameter into the method name allows to write very readable code. Even if you choose horrible variable names or use literals (as in the example above), you will still be able to make sense of the code without having to look up the method documentation.

提交回复
热议问题