user1522449
user1522449

Reputation: 3

How to pass more than One Variable Args at ObjC method?

I need to receive more than one variable Args in my method. But I don't know how to do so.

For example:

(void)insertInTableOnAttributes:(id)fieldsNames, ... Values:(id)fieldsValues, ...;

sadly it appears a compiler error after the first (...) saying:

Expected ':' after method Prototype".

And in the implementation says:

Expected Method Body" in the same position (just after the first ...)

PD: I'm using Xcode 4.2.1.

Upvotes: 0

Views: 465

Answers (2)

Lily Ballard
Lily Ballard

Reputation: 185871

You can't do that. How would the generated code possibly know where one argument list ends and the next begins? Try to think of the C equivalent

void insertInTableOnAtributes(id fieldNames, ..., id fieldValues, ...);

The compiler will reject that for the same reason.

You have two reasonable options. The first is to provide a method that takes NSArrays instead.

- (void)insertInTableOnAttributes:(NSArray *)fieldNames values:(NSArray *)fieldValues;

The second is to use one varargs with a name-value pair, similar to +[NSDictionary dictionaryWithObjectsAndKeys:]

- (void)insertInTableOnAttributes:(id)fieldName, ...;

This one would be used like

[obj insertInTableOnAttributes:@"firstName", @"firstValue", @"secondName", @"secondValue", nil];

The C analogy is actually quite accurate. An Obj-C method is basically syntactic sugar on top of a C method, so

- (void)foo:(int)x bar:(NSString *)y;

is backed by a C method that looks like

void foobar(id self, SEL _cmd, int x, NSString *y);

except it doesn't actually have a real name. This C function is called the IMP of the method, and you can retrieve it using obj-c runtime methods.

In your case of having arguments after a varargs, your

- (void)someMethodWithArgs:(id)anArg, ... andMore:(id)somethingElse;

would be backed by an IMP that looks like

void someMethodWithArgsAndMore(id anArg, ..., id somethingElse);

and since you cannot have any arguments after a varargs, this simply won't work.

Upvotes: 5

GTSouza
GTSouza

Reputation: 365

- (void)insertInTableOnAttributes:(NSArray *)fieldsNames values:(NSArray *)fieldsValues;

// Use

[self insertInTableOnAttributes:[NSArray arrayWithObject:@"name", nil] values:[NSArray arrayWithObject:@"value", nil]];

Upvotes: 0

Related Questions