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
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?
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.
In C++, we can pass parameters to a function either by pointers or by reference. In both cases, we get the same result.
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.
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.
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With