Methods with multiple arguments in objective C

前端 未结 3 695
佛祖请我去吃肉
佛祖请我去吃肉 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:29

    withArg2 is part of the method name (it is usually written without arguments as methodName:withArg2: if you want to refer to the method in the documentation), so no, it is not used for anything inside the method.

    0 讨论(0)
  • 2021-01-29 13:38

    You would call this method as follows:

    int i=[self methodName:arg1 withArg2:arg2];
    

    This is just iOs's way of making the code easier to read.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题