views:

98

answers:

2

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?

+5  A: 

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
  }
}
Iamamac
Was just going to answer the same thing. great answer!
Jacob Relkin
+6  A: 

iamamac is correct, but you also asked if there is a better way.

If at all possible, just return the value directly. Pass-by-reference is generally causes a bit of a "code smell" of the unpleasant kind.

If you need to return multiple ints, maybe you really should create a structure or a class to encapsulate the data.

bbum