How do I pass a nil-terminted list of strings to an Objective-C function?
The function [NSArray arrayWithObjects:foo, bar, nil]开发者_JAVA技巧 passes a nil-terminted list of string to a function.
If I want to write a similar function, what does the declaration look like, and how do I iterate through the strings?
I quote http://developer.apple.com/mac/library/qa/qa2005/qa1405.html, which contains the full truth.
Here's an example of an Objective-C category, containing a variadic method that appends all the objects in a nil-terminated list of arguments to an NSMutableArray instance:
#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
I'm not sure if Obj-c has its own particular support for this, but in C you do:
function nArgs(int n, ...)
To support multiple args, and the following style of implementation:
{
va_list ap;
va_start(ap, n);
while (n-- > 0) {
int i = va_arg(ap, int);
}
va_end(ap);
}
Here for more info: http://www.cprogramming.com/tutorial/lesson17.html
NSArray declares that method like this:
+ (id)arrayWithObjects:(id)firstObj, ... NS_REQUIRES_NIL_TERMINATION;
When you implement it, you'll need to use the va_arg macros to get at each argument.
Look up va_list
, va_start()
, va_arg()
, etc.
More info can be seen in the man page for va_arg
and by looking at stdarg.h
精彩评论