我需要编写一个Objective-C方法,其输入是一个字符串数组,其输出是连接的字符串列表,但只有那些不是nil的字符串。
任何想法,如果这个功能已经在基础的某个地方?
如果尚未完成,如何编写具有无限数量的NSString参数的方法?例如,就像C#中的params关键字一样,它实质上将params列表转换为数组。
感谢
答案 0 :(得分:9)
您需要...
(省略号):
- yourMessage:arg1, ...;
Here's official Apple information on the subject.
我在这里复制他们的样本:
#import <Cocoa/Cocoa.h>
@interface NSMutableArray (variadicMethodExample)
- (void) appendObjects:(id) firstObject, ...; // This method takes a nil-terminated list of objects.
@end
@implementation NSMutableArray (variadicMethodExample)
- (void) appendObjects:(id) firstObject, ...
{
id eachObject;
va_list argumentList;
if (firstObject) // The first argument isn't part of the varargs list,
{ // so we'll handle it separately.
[self addObject: firstObject];
va_start(argumentList, firstObject); // Start scanning for arguments after firstObject.
while (eachObject = va_arg(argumentList, id)) // As many times as we can get an argument of type "id"
[self addObject: eachObject]; // that isn't nil, add it to self's contents.
va_end(argumentList);
}
}
@end
答案 1 :(得分:2)
答案 2 :(得分:1)
你的答案可能就在这篇不错的帖子中。
http://cocoawithlove.com/2009/05/variable-argument-lists-in-cocoa.html