php Objective-C 默认参数值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/871796/
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
Objective-C Default Argument Value
提问by Matt Egan
Hey there, quick question here. I'm sure there's a simple answer.
嘿,在这里快速提问。我相信有一个简单的答案。
Coming from PHP, I'm used to declaring a function with a default argument value like this:
来自 PHP,我习惯于用这样的默认参数值声明一个函数:
function myFunction ($array, $sort = FALSE) {
}
I the sort parameter wasn't filled, the function would continue with the default value of false. In Obj-C, is there a similar thing?
我没有填充 sort 参数,函数将继续使用默认值 false。在 Obj-C 中,有类似的东西吗?
I'm working through the exercises in my "Programming In Objective-C 2.0" book, and it wants me to re-write a fraction class print function to default-ly not reduce the fraction, but if the value TRUE for reduce is given, go ahead and reduce the fraction, then print. The chapter (Nor nowhere in the book) gives any information on this.
我正在完成我的“Objective-C 2.0 编程”一书中的练习,它希望我重新编写一个分数类打印函数来默认不减少分数,但如果给出了 reduce 的值 TRUE ,继续减少分数,然后打印。本章(本书中也没有)提供了有关此的任何信息。
Thanks for your help guys :D
谢谢你们的帮助:D
回答by Chuck
Default arguments don't exist in Objective-C, per se. They can't really, because the argument count is inextricably tied to the method name — each colon corresponds to one argument.
Objective-C 本身不存在默认参数。他们真的不能,因为参数计数与方法名称密不可分——每个冒号对应一个参数。
Objective-C programmers accomplish a similar goal, though, by creating "convenience" methods that just call to a more "primitive" method with some of the arguments filled in with default values. For example, -[NSArray indexOfObject:]could be implemented as version of -[NSArray indexOfObject:inRange:]with an argument of NSMakeRange(0, [self count])for the inRange:part.
然而,Objective-C 程序员通过创建“方便”的方法来实现类似的目标,这些方法只调用更“原始”的方法,其中一些参数填充有默认值。例如,-[NSArray indexOfObject:]可以实现为的版本-[NSArray indexOfObject:inRange:]与一个参数NSMakeRange(0, [self count])的inRange:一部分。
In this case, though, I don't think your book is talking about that. I think it simply means to reduce the fraction if YES is given for the reduce:argument and not reduce it if NO is given.
不过,在这种情况下,我不认为你的书在谈论这个。我认为这只是意味着如果为reduce:参数给出 YES 则减少分数,如果给出NO 则不减少它。
回答by bbum
There are two standard patterns for achieving what you want.
有两种标准模式可以实现你想要的。
(1) write a many argument form of a method and then provide fewer argument convenience versions. For example, consider the following methods on NSString:
(1) 编写方法的多参数形式,然后提供较少参数的便利版本。例如,考虑 NSString 上的以下方法:
- (NSComparisonResult)compare:(NSString *)string;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
range:(NSRange)compareRange;
- (NSComparisonResult)compare:(NSString *)string options:(NSStringCompareOptions)mask
range:(NSRange)compareRange locale:(id)locale;
The first three are conceptually [and likely concretely, I didn't check] implemented as calls through to the fourth version. That, is -compare: calls -compare:options:range:locale: with appropriate default values for the three additional arguments.
前三个在概念上 [并且可能具体地,我没有检查] 作为调用实现到第四个版本。即 -compare: 调用 -compare:options:range:locale: 三个附加参数的适当默认值。
(2) The other pattern is to implement the many argument version of the method and provide default values when an argument is NULL/nil or set to some value that indicates the default is desired. NSData has methods that are implemented with this pattern. For example:
(2) 另一种模式是实现该方法的多参数版本,并在参数为 NULL/nil 或设置为指示需要默认值的某个值时提供默认值。NSData 具有使用此模式实现的方法。例如:
+ (id)dataWithContentsOfFile:(NSString *)path options:(NSDataReadingOptions)readOptionsMask
error:(NSError **)errorPtr;
If you pass 0 for the readOptionsMask argument, the NSData will read the contents of the file using an internally defined default configuration. That default configuration may change over time.
如果为 readOptionsMask 参数传递 0,NSData 将使用内部定义的默认配置读取文件的内容。该默认配置可能会随着时间的推移而改变。
回答by Shadow Radiance
This question is super old, but in case anyone finds it, the Objective-C version of the PHP code (assuming this is inside a class) would probably be something like this:
这个问题非常古老,但万一有人找到它,PHP 代码的 Objective-C 版本(假设这是在一个类中)可能是这样的:
-(id)myFunction:(NSArray*)array {
return [self myFunction:array withSort:FALSE];
}
-(id)myFunction:(NSArray*)array withSort:(BOOL)useSort {
// CODE
}
I used (id)s as there is no data type information in your PHP code. Replacing the (id)s with actual data types would be wise.
我使用了 (id)s,因为您的 PHP 代码中没有数据类型信息。用实际数据类型替换 (id) 是明智的。
回答by shilgapira
Terrible necro but for anyone googling this, Xcode 4.5 supports (via Clang) overloading of C functions with __attribute__((overloadable)).
可怕的死灵,但对于任何使用谷歌搜索的人来说,Xcode 4.5 支持(通过Clang)使用__attribute__((overloadable)).
Overloaded functions are allowed to have different numbers of arguments, so if C functions are appropriate for what you're trying to do you can use that to get default argument values.
允许重载函数具有不同数量的参数,因此如果 C 函数适合您尝试执行的操作,您可以使用它来获取默认参数值。
Here's a contrived example of an .h file with two functions, both called PrintNum:
这是一个带有两个函数的 .h 文件的人为示例,两个函数都称为PrintNum:
// Prints a number in the decimal base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number);
// Prints a number in the specified base
__attribute__((overloadable)) extern void PrintNum(NSNumber *number, NSUInteger base);
and in the .m file:
并在 .m 文件中:
__attribute__((overloadable))
void PrintNum(NSNumber *number) {
PrintNum(number, 10);
}
__attribute__((overloadable))
void PrintNum(NSNumber *number, NSUInteger base) {
// ...
}
Note that the attribute must be specified in all definitions and declarations of the function.
请注意,必须在函数的所有定义和声明中指定该属性。
回答by rein
No, default arguments are a feature of C++, not C or Objective-C.
不,默认参数是 C++ 的特性,而不是 C 或 Objective-C。
What you would have to do in objective-c is the following (using your psuedo code above):
您在objective-c中必须做的事情如下(使用上面的伪代码):
function myFunction ($array, $sort)
function myFunction ($array)
// call myFunction($array, FALSE)
回答by Rick Cheung
You can easily achieve the same effect using #define.
您可以使用 轻松实现相同的效果#define。
The function in your header file:
头文件中的函数:
+(NSDate*)getDateFromYear:(NSUInteger)year month:(NSUInteger)month day:(NSUInteger)day;
Add a #definefor parameter function in header file:
#define在头文件中添加一个for参数函数:
#define GetDateFromYearOnly(year) [YourClassName getDateFromYear:year month:1 day:1]
Then your can use the function like:
然后你可以使用这样的功能:
NSDate* 2015Date = GetDateFromYearOnly(2015);
And you will get an NSDateobject with date 2015/01/01.
你会得到一个NSDate日期为 2015/01/01的对象。
If the function is not static, build a new function like this:
如果函数不是static,则构建一个新函数,如下所示:
-(NSDate*)GetDateFromYearOnly:(NSUInteger)year;
And call:
并调用:
[self getDateFromYear:year month:1 day:1]

