Re: Variable argument methods
Re: Variable argument methods
- Subject: Re: Variable argument methods
- From: Brent Gulanowski <email@hidden>
- Date: Thu, 10 Jul 2003 21:07:13 -0400
On Thursday, July 10, 2003, at 07:24 PM, Matt Diephouse wrote:
Hi. I'm new to Cocoa and Objective-C. I've only done programming in
Perl, Ruby, and Python before.
I'm trying to write a method that takes a variable number of
arguments. I've searched the archives and the net for examples, but
haven't understood anything I've come up with. I want to take the
following method (which is untested) and make so I'm not using an
array to pass arguments.
- (BOOL)sendCommand: (NSString *)cmd
withArgs: (NSArray *)args;
Here's an example of how I want its usage to look.
[class sendCommand:@"article"
withArgs:@"one", @"two", @"three"];
I think I need to use va_list and and associated functions, but I'm
not sure how they work. I've also seen it mentioned that two methods
are actually needed. Could someone please explain this for me? Please
keep in mind that I'm not used to dealing with types this way, having
come from a predominantly Perl background. Thanks,
va_start(), va_arg() and va_end() are macros, not functions. This
allows va_arg() to return the type specified in its second argument; a
function could not do this. You have to have some way of knowing the
types of the arguments in the variable argument list. In your case, it
looks like they are all strings, so you can just assume that.
-(void)sendCommand:(NSString *)cmd withArgs:(NSString * )argument, ... {
va_list ap;
va_start( ap, argument );
while( argument != nil ) {
// do whatever with your string object
argument = va_arg( ap, NSString *);
}
va_end( ap );
return YES; // or NO
}
In more complex situations, (eg.: see "man stdarg") you might pass a
string with formatting that specifies a variable argument list of
varying types.
va_start() initializes the list using the location of the immediately
preceding argument. successive calls to va_arg() return the value of
the type specified (so they have to match).
How it works internall, I cannot quite say. stdarg.h is not pretty.
Brent Gulanowski email@hidden
--
keyboard not found, press F1 to continue
_______________________________________________
cocoa-dev mailing list | email@hidden
Help/Unsubscribe/Archives:
http://www.lists.apple.com/mailman/listinfo/cocoa-dev
Do not post admin requests to the list. They will be ignored.