变量函数:检查参数数量

时间:2023-02-01 23:16:29

I have a variadic function that runs some code on the first argument and then runs NSString initWithFormat:arguments: afterwards, if arguments have been passed in.

我有一个可变函数,它在第一个参数上运行一些代码,然后运行NSString initWithFormat:arguments:之后,如果传入了参数。

+ (NSString *)updatedString:(NSString *)mainString, ...
{
    // Some code run on mainString here, outputs finalString

    // add format arguments to the final string
    va_list args;
    va_start(args, mainString);
    NSString *formattedString = [[NSString alloc] initWithFormat:finalString arguments:args];
    va_end(args);

    return formattedString;
}

EDIT: The idea is that the code run on mainString uses a regular expression to find and replace variables within the text. So say the output (finalString) equals "Hello World %@ blah blah %@", then it would use the arguments to replace the %@ symbols. The issue is that I don't know if the resolved string includes %@ symbols or not until the string is resolved.

编辑:这个想法是在mainString上运行的代码使用正则表达式来查找和替换文本中的变量。所以说输出(finalString)等于“Hello World%@ blah blah%@”,然后它会使用参数来替换%@符号。问题是,在解析字符串之前,我不知道解析后的字符串是否包含%@符号。

So, I need to check to see if there are actually any extra arguments, and if there aren't, I don't want to run the initiWithFormat part.

所以,我需要检查是否有任何额外的参数,如果没有,我不想运行initiWithFormat部分。

Is there any way to check if args exists first?

有没有办法检查args是否先存在?

1 个解决方案

#1


No. In C/Objective-C a called variadic function has absolutely no idea about the number and types of arguments passed by the caller. It must figure it out somehow based on other information (e.g. for format arguments, that they match the format specifiers in the format string; or for objects to initialize a Cocoa collection, that the list is terminated with nil) and trust that the caller correctly followed the convention.

在C / Objective-C中,一个被称为可变参数的函数完全不知道调用者传递的参数的数量和类型。它必须根据其他信息(例如格式参数,它们与格式字符串中的格式说明符匹配;或者对于初始化Cocoa集合的对象,列表以nil终止)并且信任调用者正确遵循惯例。

#1


No. In C/Objective-C a called variadic function has absolutely no idea about the number and types of arguments passed by the caller. It must figure it out somehow based on other information (e.g. for format arguments, that they match the format specifiers in the format string; or for objects to initialize a Cocoa collection, that the list is terminated with nil) and trust that the caller correctly followed the convention.

在C / Objective-C中,一个被称为可变参数的函数完全不知道调用者传递的参数的数量和类型。它必须根据其他信息(例如格式参数,它们与格式字符串中的格式说明符匹配;或者对于初始化Cocoa集合的对象,列表以nil终止)并且信任调用者正确遵循惯例。