how to pass multiple arguments in a single function in Objective-C? I want to pass 2 integer values and the return value is also integer. I want to use the new Objective-C syntax, not the old C/C++ syntax.
4 Answers
In objective-c it is really super easy. Here is the way you would do it in C:
int functName(int arg1, int arg2)
{
// Do something crazy!
return someInt;
}
This still works in objective-c because of it's compatibility with C, but the objective-c way to do it is:
// Somewhere in your method declarations:
- (int)methodName:(int)arg1 withArg2:(int)arg2
{
// Do something crazy!
return someInt;
}
// To pass those arguments to the method in your program somewhere:
[objectWithOurMethod methodName:int1 withArg2:int2];
Best of luck!
3 Comments
ericn
When you say "super easy", it's opinionated, I'm afraid. How does "methodName ... withArg2" makes more sense than "functName"? I'd rather just describe this as recommended approach by Apple. Also, one can always do something like
-(int)functName:(int)arg1 :(int)arg2ellmo
I agree,
withArg2 is hardly super easy and legible. What if someone wanted a method accepting five arguments? Would they have to use withArg3, withArg4 and so on?Alex Blakemore
The syntax is borrowed from SmallTalk and allows you to intersperse the argument names with the method name, but the text prefix is optional. The required part is the colon to indicate each positional argument. The following works for example -(void) moveTo:(int)x :(int)y and can be called as [somebody moveTo:42 :64]
Since this is still google-able and there are better solutions than the accepted answer; there's no need for the hideous withArg2 – just use colons:
Declaration:
@interface
-(void) setValues: (int)v1 : (int)v2;
Definition:
@implementation
-(void) setValues: (int)v1 : (int)v2 {
//do something with v1 and v2
}
Comments
Like this:
int sum(int a, int b) {
return a + b;
}
Called like this:
int result;
result = sum(3, 5);
// result is now 8
3 Comments
V.V
sorry boss, i need the code in objective c not in simple c or c++
T.J. Crowder
@Viral: That is Objective-C. See the link.
T.J. Crowder
@Viral: I've updated your question to make it clearer what you were looking for. Remember that the clearer you make your question, the higher the quality of answers you'll get.
int add (int a, int b)
{
int c;
c = a + b;
return c;
}
2 Comments
T.J. Crowder
You could at least tell the OP where you copied and pasted that from (en.wikibooks.org/wiki/Objective-C_Programming/syntax).
V.V
sorry dear, i need the answer in objective c language, not in c or c++.