Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing integer by reference

I have a class level int defined in my header file. In the .m file, I have a method that I'd like to take an int parameter, modify it and have the modified value reflected at the caller. For example:

classLevelInt = 2;
[self someMethod:classLevelInt];

//Here, I'd like classLevelInt to equal the value assigned to it in the method

In -someMethod:

- (void)someMethod:(int)anInt{
//do some stuff
if(somecondition){
  anInt = 2 + 3; //some operation
}
}

I've tried using an

  • NSNumber
  • Pointer of a pointer (**)
  • Converting int to NSNumber inside the method, which results in a new address space

but never see the value set inside the method for classLevelInt reflected outside of that method. Without returning the new int value from -someMethod, how can I have the value of classLevelInt preserve outside of the method? Or, if that is simply not a good approach, what is a better way?

like image 900
4thSpace Avatar asked Jan 01 '10 00:01

4thSpace


People also ask

Is integer object pass by reference?

Integer is pass by value, not by reference. Changing the reference inside a method won't be reflected into the passed-in reference in the calling method. Integer is immutable.

Can you pass an integer by reference C++?

In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result.

How do you pass by reference?

Pass-by-reference means to pass the reference of an argument in the calling function to the corresponding formal parameter of the called function. The called function can modify the value of the argument by using its reference passed in. The following example shows how arguments are passed by reference.

Is integer passed by reference in Python?

If you pass immutable arguments like integers, strings or tuples to a function, the passing acts like Call-by-value. It's different, if we pass mutable arguments. All parameters (arguments) in the Python language are passed by reference.


1 Answers

You can pass a pointer to classLevelInt as int*.

classLevelInt = 2;
[self someMethod:&classLevelInt];

- (void)someMethod:(int*)anInt {
  //do some stuff
  if(somecondition){
    *anInt = 2 + 3; //some operation
  }
}

A second way, you can directly change classLevelInt in the same class.

- (void)someMethod {
  //do some stuff
  if(somecondition){
    classLevelInt = 2 + 3; //some operation
  }
}
like image 164
iamamac Avatar answered Oct 13 '22 22:10

iamamac