function with multiple arguments - objective-c

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.

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!

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
}

Like this:
int sum(int a, int b) {
return a + b;
}
Called like this:
int result;
result = sum(3, 5);
// result is now 8
More here

int add (int a, int b)
{
int c;
c = a + b;
return c;
}
link text

Related

return of a local variable by ref works

Take a look at this C++ code:
#include <iostream>
using namespace std;
class B{
public:
int& f() {
int local_n = 447;
return local_n ;
} // local_n gets out of scope here
};
int main()
{
B b;
int n = b.f(); // and now n = 447
}
I don't understand why n = 447 at the end of main, because I tried to return a reference to a local_n, when it should be NULL;
Returning a reference to a local variable invokes undefined behavior - meaning you might get lucky and it might work... sometimes... or it might format your hard drive or summon nasal demons. In this case, the compiler generated code that managed to copy the old value off the stack before it got overwritten with something else. Oh, and references do not have a corresponding NULL value...
Edit - here's an example where returning a reference is a bad thing. In your example above, since you copy the value out of the reference immediately before calling anything else, it's quite possible (but far from guaranteed) that it might work most of the time. However, if you bind another reference to the returned reference, things won't look so good:
extern void call_some_other_functions();
extern void lucky();
extern void oops();
int& foo()
{ int bar = 0;
return bar;
}
main()
{ int& x = foo();
x = 5;
call_some_other_functions();
if (x == 5)
lucky();
else
oops();
}

How to declare a C function with an undetermined return type?

Can I declare a C function with an undetermined return type (without C compiler warning)? The return type could be int, float, double, void *, etc.
undetermined_return_type miscellaneousFunction(undetermined_return_type inputValue);
And you can use this function in other functions to return a value (although that could be a run time error):
BOOL isHappy(int feel){
return miscellaneousFunction(feel);
};
float percentage(float sales){
return miscellaneousFunction(sales);
};
What I'm looking for:
To declare and to implement a C function (or Obj-C method) with an undefined-return-type could be useful for aspect-oriented programming.
If I could intercept Obj-C messages in another function in run time, I might return the value of that message to the original receiver or not with doing something else action. For example:
- (unknown_return_type) interceptMessage:(unknown_return_type retValOfMessage){
// I may print the value here
// No idea how to print the retValOfMessage (I mark the code with %???)
print ("The message has been intercepted, and the return value of the message is %???", retValOfMessage);
// Or do something you want (e.g. lock/unlock, database open/close, and so on).
// And you might modify the retValOfMessage before returning.
return retValOfMessage;
}
So I can intercept the original message with a little addition:
// Original Method
- (int) isHappy{
return [self calculateHowHappyNow];
}
// With Interception
- (int) isHappy{
// This would print the information on the console.
return [self interceptMessage:[self calculateHowHappyNow]];
}
You can use a void * type.
Then for example:
float percentage(float sales){
return *(float *) miscellaneousFunction(sales);
}
Be sure not to return a pointer to a object with automatic storage duration.
You may use the preprocessor.
#include <stdio.h>
#define FUNC(return_type, name, arg) \
return_type name(return_type arg) \
{ \
return miscellaneousFunction(arg); \
}
FUNC(float, undefined_return_func, arg)
int main(int argc, char *argv[])
{
printf("\n %f \n", undefined_return_func(3.14159));
return 0;
}
May be a union as suggested by thejh
typedef struct
{
enum {
INT,
FLOAT,
DOUBLE
} ret_type;
union
{
double d;
float f;
int i;
} ret_val;
} any_type;
any_type miscellaneousFunction(any_type inputValue) {/*return inputValue;*/}
any_type isHappy(any_type feel){
return miscellaneousFunction(feel);
}
any_type percentage(any_type sales){
return miscellaneousFunction(sales);
}
Here with ret_type you can know data type of return value and ret_type. i,f,d can give you corresponding value.
All elements will use same memory space and only one should be accessed.
Straight C doesn't support dynamically-typed variables (variants) since it is statically typed, but there might be some libraries that do what you want.

Objective C equivalent of C method signature

I want make a function to include in my code to calculate percentages.
In Php, it's :
function percent(a,b){
return a/b*100;
}
In Objective C, I don't know. I tried:
-(void)percent(a,b){
return a/b*100;
}
But there are 2 errors. Could you me explain how to make it work?
Thank you for you help
A method is defined in a slightly different syntax than you're used to:
- (float)percentWithA:(float)a dividedByB:(float)b
{
return a / b * 100;
}
The parameters are "strewn" throughout the method call. For instance, this method's name would be percentWithA:dividedByB:. You don't need to be as explicit as this call, however. For example, you could do this:
- (float)percent:(float)a :(float)b { /* ... */ }
But it doesn't provide much context.
The more correct way to do this will be:
- (float)precentageByDevidingFloat:(float)a byFloat:(float)b {
float returnValue = 0;
if (b != 0)
returnValue = a / b * 100;
return returnValue;
}
This way you use a more correct naming convention , you actually return a float and your safe in case some one gave you the value 0 in B.
(which should be covered by documentation)
You could also do it like this, with a C function:
// in your .h
float percent(float a, float b);
// in your .m or .c
float percent(float a, float b)
{
return a / b * 100.0f;
}
Or, if you are into macros:
// remember to always enclose macros in parentheses
#define percent(a, b) (a / b * 100.0f)
And you would call it like this:
percent(50, 20);
Objective-C uses a strange convention of having parameter names as part of a method name and therefore parameter declarations are embedded in a method name.
-(float)percentOf:(float)a over:(float)b
{
return (a/b) * 100.0;
}
The first type in parentheses defines the return type, the parameters come after colons and also have their type in parentheses.

error C3698: 'CreerLevel::Mur ^' : impossible d'utiliser ce type comme argument de 'nouveau'

i have create one class and i need to use it with vector.
ref class Mur
{
public:
int debutX, debutY;
int finX, finY;
Mur (){}
Mur(int debutX, int debutY) {
this->debutX = debutX;
this->debutY = debutY;
finX = 0;
finY = 0;
}
~Mur()
{
}
int getX() { return debutX; }
int getY() { return debutY; }
bool estFinit() {
return (finX==0);
}
void finir(int x, int y){
finX = x;
finY = y;
}
};
}
When i try to use it
std::vector<Mur^> vMurs;
...
vMurs.push_back(gcnew Mur(i,j));
Error come in file "xmemory" at line 52 but i don't know this file xD
The compiler is objecting because you're trying to store a managed object in an unmanaged class. That cannot work, the garbage collector needs to be able to find object references so it can properly collect garbage. And since it cannot find unmanaged objects, it cannot find the managed reference either.
I'd strongly advice to not use STL/CLR, it combines all the disadvantages of STL with those of the CLR. If you really, really want to use vector<> then gcroot<> can solve the problem. However, using System::Collections::Generic::List<> is by far the best solution.
using namespace System::Collections::Generic;
...
List<Mur^>^ vMurs = gcnew List<Mur^>;
...
vMurs->Add(gcnew Mur(i, j));
I agree with Alexandre C. If you want to use a vector, you could use the STL/CLR (http://msdn.microsoft.com/en-us/library/bb385954.aspx) vector.
Try using
std::vector<gcroot<Mur ^> > vMurs;
...
vMurs.push_back(gcnew Mur(i,j));

Declaring and using a C function in Objective C

This must be very simple, but I can't figure out how to do this: I have a C-function to monitor current memory usage:
natural_t report_memory(void) {
struct task_basic_info info;
mach_msg_type_number_t size = sizeof(info);
kern_return_t kerr = task_info(mach_task_self(),
TASK_BASIC_INFO,
(task_info_t)&info,
&size);
if( kerr == KERN_SUCCESS ) {
return info.resident_size;
} else {
NSLog(#"Error with task_info(): %s", mach_error_string(kerr));
return 0;
}
}
Now, I would like to use it. How do I declare it in the .h?
I tried the (for me) obvious within the objective c methods:
natural_t report_memory(void);
Calling this somewhere in the code:
NSLog(#"Memory used: %u", rvC.report_memory());
The Compiler complains error: called object is not a function. Thus, I assume, the declaration is somehow wrong. I tried several options, but the best I could get was a runtime error...
How to fix this?
rvC.report_memory()
should be replaced with
report_memory()
since it is a C function.
If you want to use this function in other modules, you should also put in your header (.h) file this line
extern natural_t report_memory(void);