Empty method name, what does this actually do?

后端 未结 2 1372
小鲜肉
小鲜肉 2021-01-02 07:08

I\'m currently learning myself objective-c and iOS programming and found myself stuck with non-working code due to this subtle error for an hour. Consider the following code

相关标签:
2条回答
  • 2021-01-02 07:33

    A method declare like the one you posted is rare (and poor style, imo). Objective-C is supposed to be verbose. Methods break down like this:

    1. First character: Either - or +. - means it is an instance method, + means it is a class method.
    2. Value in parentheses: The return type of the method. In your example, the method returns an (NSString *).
    3. The rest (before the curly braces) is the method name along with any parameters they take. You could have a name with no parameters, in which case the method name would not have a : in it. Such as - (void) reload; This would be a method that doesn't return a value and takes no parameters.
    4. If your method takes parameters, they will be mixed into the method name and usually will declare the type (unlike your example). Such as - (NSString *) reverseString:(NSString *) stringToReverse; In this example your method name would be reverseString: it takes one parameter, an NSString* that will be called stringToReverse in the method definition.
    5. Usually, if you see a : with no type it will be a case like - (float) addThreeValues::: This method returns a float and takes 3 parameters. This would be an appropriate definition because the three values don't matter what order they are provided because we are just adding them.
    0 讨论(0)
  • The method signature - (NSString *):name breaks down to the following:

    • - It is an instance method (versus a class method with a +).
    • (NSString *) It returns a string.
    • : If you were to speak the name of this method, it would simply be called "colon". : tells the compiler that your method accepts one parameter as well.
    • name There is a parameter called name.

    When you don't specify a type, the compiler assumes you meant id, so this method actually fleshes out to be - (NSString *):(id)hello

    A valid call to this method would be: [self :@"hello"].

    You can do really weird things because : is a valid name for a method, and the compiler assumes id. You could, if you really wanted to, have a method called - :::. The compiler would assume you meant - (id):(id):(id):(id), a method that returns an object of type id and takes three parameters of type id. You'd call it like so: [self :@"hello" :anObject :myObject];

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