开发者

how to pass n argunment to the method

example

add(int a, int b) Here we pass two argument int a, int b,

can we pass n argument with different data types like int,float,long, is it possible?

I means i need to write only one m开发者_开发技巧ethod which handles n Arguments.


Yes, it is possible to pass arguments with different data types to Objective-C methods. I assume you're speaking about Objective-C, since the question is tagged iphone.

For example, you could have a method like:

- (void)foo:(int)foo bar:(float)bar baz:(long)baz {
    // ...
}

If you are talking about C, you could have a function:

void myfunc(int foo, float bar, long baz) {
    // ...
}

If you want to write functions that have variable sized argument lists (so it can take 1 parameter, or 2 parameters, or 3, ...), I suggest you take a look at this blog post which discusses variable argument lists in Objective-C/Cocoa or Apple's technical Q&A on variable argument lists.


- (int)add:(int)number1 to:(int)number2 {
         return number1 + number2;
}

call it using [obj add:2 to:4]; where obj is the object receiving the add message.

You may use any type of arguments in the above to achieve what you have in mind. For example:

- (void)add:(int)number1 to:(float)number2 {
         //print result here
}

Standard type conversions etc would apply like in any programming language.

If you are talking about totally arbitrary number of arguments, take a look at Variadic functions in Objective C (Google it). Plenty of good tutorials in the first search results page.


Anything is possible, but I am pretty certain it would require some serious hacking to get it to work for variable data types. If you can change the requirements to be a variable number of specific data type, then you should look at an excellent tutorial at "Cocoa with Love" : variable-argument-lists-in-cocoa

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜