Cocoa - 从另一个可变参数方法调用可变参数方法(NSString stringWithFormat 调用)
我对 [NSString strigWithFormat:format]
有问题,因为它返回一个 id,并且我有很多代码将 NSString var 更改为其他个人类型。但编译器不会阻止我在某些地方将 NSString 设置为另一种类型的对象。
因此,我正在编写一个 NSString 类别,并且将对 stringWithFormat
的所有调用替换为 myStringWithFormat
。
代码是:
@interface NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format;
@end
@implementation NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format {
return (NSString*)[NSString stringWithFormat:format];
}
@end
编译器告诉我“格式不是字符串文字,也没有格式参数”。
你有什么办法可以让这项工作发挥作用吗?
I have a problem with [NSString strigWithFormat:format]
because it returns an id, and I have a lot of code where I changed a NSString var to an other personal type. But the compiler does not prevent me that there are places where a NSString is going to be set into another type of object.
So I'm writing a category of NSString and I'm goind to replace all my calls to stringWithFormat
to myStringWithFormat
.
The code is :
@interface NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format;
@end
@implementation NSString (NSStringPerso)
+ (NSString*) myStringWithFormat:(NSString *)format {
return (NSString*)[NSString stringWithFormat:format];
}
@end
The compiler tells me that "Format not a string literal and no format arguments".
Do you see any way to make this work ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
NSString 包含一个从可变参数函数中获取参数列表的方法。看一下这个示例函数:
其中一些代码是不相关的,但关键行是
NSString *output = [[NSString alloc] initWithformat:format Arguments:arguments];
。这就是如何在可变参数函数/方法中构造NSString
。对于您的情况,您的代码应如下所示:
NSString
includes a method that takes in an argument list from a variadic function. Look at this sample function:Some of that code is irrelevant, but the key line is
NSString *output = [[NSString alloc] initWithformat:format arguments:arguments];
. That's how you can construct anNSString
in a variadic function/method.In your case, your code should look something like this:
这里没有 Objective-C 专家,但是
stringWithFormat
的原始方法签名包含省略号,它允许您传入将要替换为argument.
编辑:
stringWithFormat
是所谓的可变参数方法。这是示例的链接。No Objective-C expert here, but the original method signature for
stringWithFormat
includes ellipses, which allows you to pass in the arguments that are going to be substituted to the placeholders in the formatargument
.EDIT:
stringWithFormat
is a so-called variadic method. Here's a link to an example.感谢您的帮助。
阅读您的参考文档,我找到了解决方案!
这有效:
在 .h 中
在 .m 中
Thank you for your help.
Reading your reference documentations, I found the solution !
This works :
In the .h
In the .m