Optional arguments in Objective-C 2.0?

前端 未结 5 597
旧巷少年郎
旧巷少年郎 2020-12-04 21:04

In Objective-C 2.0, is it possible to make a method where the argument is optional? That is, you can have a method call like this:

[aFraction print];
         


        
5条回答
  •  失恋的感觉
    2020-12-04 21:57

    The way you did it is the right way to do it in Objective-C. It's used extensively in Cocoa itself. For example, some of NSString's initializers:

    – initWithFormat:  
    – initWithFormat:arguments:  
    – initWithFormat:locale:  
    – initWithFormat:locale:arguments:
    

    The reason it works is because the : is part of the method name, so as far as the compiler is concerned, print and print: are completely different messages that are no more closely connected than "print" and "sprint".

    However, the particular names of the methods you gave aren't a very good case for this, because it's unclear from the name what the parameter is (or what "print" by itself means if the parameter is what the object prints). It would be better to have, say, printFalseMessage and printMessageWithFlag:.

提交回复
热议问题