Objective-C 2.0 中的可选参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/561185/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 21:09:19  来源:igfitidea点击:

Optional arguments in Objective-C 2.0?

objective-c

提问by willc2

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:

在 Objective-C 2.0 中,是否可以创建一个参数可选的方法?也就是说,你可以有一个这样的方法调用:

[aFraction print];

as well as this:

还有这个:

[aFraction print: someParameter];

in the same program.

在同一个程序中。

Apple's Objective-C 2.0 Programming Languageguide contrasts Obj-C with Python and seems to say this is not allowed. I'm still learning and I want to be sure. If it ispossible, then what is the syntax, because my second code example does not work.

Apple 的Objective-C 2.0 编程语言指南将 Obj-C 与 Python 进行了对比,似乎说这是不允许的。我还在学习,我想确定一下。如果它可能的,那么什么是语法,因为我的第二个代码示例不起作用。

Update:OK, I just made two methods, both named "print".

更新:好的,我刚刚做了两个方法,都命名为“print”。

header

标题

-(void) print;
-(void) print: (BOOL) someSetting; 

implementation

执行

-(void) print {
    [self print:0];
}

-(void) print: (BOOL) someSetting {
    BOOL sv;
    sv = someSetting;

    if ( sv ) {
        NSLog(@"cool stuff turned on");
    }
    else {
        NSLog(@"cool stuff turned off");
    }
}

the relevant program lines

相关的程序行

    ...
    printParamFlag = TRUE;

// no parameter
    [aCodeHolder print];

// single parameter
    [aCodeHolder print:printParamFlag];
    ...

I can't believe that worked. Is there any reason I shouldn't do this?

我不敢相信这奏效了。有什么理由我不应该这样做吗?

回答by Georg Sch?lly

You can declare multiple methods:

您可以声明多个方法:

- (void)print;
- (void)printWithParameter:(id)parameter;
- (void)printWithParameter:(id)parameter andColor:(NSColor *)color;

In the implementation you can do this:

在实现中,您可以这样做:

- (void)print {
    [self printWithParameter:nil];
}

- (void)printWithParameter:(id)parameter {
    [self printWithParameter:nil andColor:[NSColor blackColor]];
}

Edit:

编辑:

Please do not use printand print:at the same time. First of all, it doesn't indicate what the parameter is and secondly no one (ab)uses Objective-C this way. Most frameworks have very clear method names, this is one thing that makes Objective-C so pain-free to program with. A normal developer doesn't expect this kind of methods.

请不要同时使用printprint:。首先,它没有指明参数是什么,其次没有人 (ab) 以这种方式使用 Objective-C。大多数框架都有非常明确的方法名称,这是使 Objective-C 编程变得如此轻松的一件事。一个普通的开发者不会期望这种方法。

There are better names, for example:

有更好的名字,例如:

- (void)printUsingBold:(BOOL)bold;
- (void)printHavingAllThatCoolStuffTurnedOn:(BOOL)coolStuff;

回答by Chuck

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:

你这样做的方式是在 Objective-C 中做的正确方法。它在 Cocoa 本身中被广泛使用。例如,一些 NSString 的初始值设定项:

– 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, printand print:are completely different messages that are no more closely connected than "print" and "sprint".

它的工作原理的原因是因为:是方法名称的一部分,所以只要编译器而言,printprint:是大于“打印”和“冲刺”没有连接更紧密完全不同的消息。

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, printFalseMessageand printMessageWithFlag:.

但是,您给出的方法的特定名称并不是一个很好的例子,因为从名称中不清楚参数是什么(或者如果参数是对象打印的内容,则“打印”本身意味着什么)。最好有,比如说,printFalseMessageprintMessageWithFlag:

回答by Matt Gallagher

Another option for multiple optional arguments is to pass them all in an NSDictionary:

多个可选参数的另一种选择是将它们全部传递到 NSDictionary 中:

- (void)someMethodWithOptions:(NSDictionary *)options;

then declare that the options dictionary may contain:

然后声明选项字典可能包含:

- key1, value must be a BlahObject
- key2, value must be a NonBlahObject

you can then allow any of the keys to be absent and even the dictionary itself could be nil.

然后,您可以允许不存在任何键,甚至字典本身也可以为零。

回答by Erik Engheim

Slightly related you can have optional arguments. Meaning you can call a method with any number of arguments if you like. But that is a feature from C (varargs).

稍微相关,您可以有可选参数。这意味着您可以根据需要调用具有任意数量参数的方法。但这是 C (varargs) 的一个特性。

An example, is the NSArraymessage:

一个例子是NSArray消息:

+ (id)arrayWithObjects:(id)firstObj, ...

Example of usage:

用法示例:

NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = @"a string";

myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];

This is straight from the Apple docs. You indicate the end of all your arguments with a nil.

这是直接来自 Apple 文档。您用nil表示所有参数的结尾。

回答by John Wilund

To avoid the Parse issue: 'aVariable' used as the name of the previous parameter rather than as part of the selectoryou get from the compiler as a warning you should do:

为避免解析问题: 'aVariable' 用作前一个参数的名称,而不是作为从编译获得的选择器的一部分作为警告,您应该这样做:

- (void)printWithParameter:(BOOL)sv color:(NSColor *)color{
   // your cool code goes here
   if ( sv ) {
      NSLog(@"cool stuff turned on");
   }
   else {
      NSLog(@"cool stuff turned off");
   }
}

and you could call the method, such:

您可以调用该方法,例如:

[self printWithParameter:NO color:[UIColor someColor]] // NO instead of 0

or

或者

[self printWithParameter:YES color:[UIColor someColor]] // YES instead of 1