Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass values by reference in objective C (iphone)

Tags:

objective-c

People also ask

Can you pass an object by reference?

A mutable object's value can be changed when it is passed to a method. An immutable object's value cannot be changed, even if it is passed a new value. “Passing by value” refers to passing a copy of the value. “Passing by reference” refers to passing the real reference of the variable in memory.

What does @() mean in Objective-C?

It's Shorthand writing. In Objective-C, any character , numeric or boolean literal prefixed with the '@' character will evaluate to a pointer to an NSNumber object (In this case), initialized with that value. C's type suffixes may be used to control the size of numeric literals.

How do you pass value by reference?

To pass a value by reference, argument pointers are passed to the functions just like any other value. So accordingly you need to declare the function parameters as pointer types as in the following function swap(), which exchanges the values of the two integer variables pointed to, by their arguments.

Is Objective-C pass by reference?

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call.


Pass-by-reference in Objective-C is the same as it is in C.

The equivalent to the following C# code:

void nullThisObject(ref MyClass foo)
{
    foo = null;
}

MyClass bar = new MyClass();
this.nullThisObject(ref bar);
assert(bar == null);

is

- (void)nilThisObject:(MyClass**)foo
{
    [*foo release];
    *foo = nil;
}

MyClass* bar = [[MyClass alloc] init];
[self nilThisObject:&bar];
NSAssert(bar == nil);

and

- (void)zeroThisNumber:(int*)num
{
    *num = 0;
}

int myNum;
[self zeroThisNumber:&myNum];
NSAssert(myNum == 0);

If you use Objective C++, which you can do by naming your file with extension .mm, or telling Xcode to compile all source as Objective C++, then you can pass references in the same way you do with C++, eg:

- (OSStatus) fileFileInfo: (FileInfo&)fi;

There is no passing by reference (in C++ sense) in Objective C. You can pass your objects by pointer, and for primitive types by value.

Example:

void func(NSString* string)
{
  ...
}

void func(NSInteger myint)
{
 ...
}

..
NSString* str = @"whatever";
NSInteger num = 5;

func(str);
func(num); 

Try this way :

    -(void)secondFunc:(NSInteger*)i
    {
      *j=20;
     //From here u can change i value as well
     //now i and j value is same (i.e i=j=20)
    }
    -(void) firstFunc
    {
       NSInteger i=5;
      [self secondFunc :&i];
     //i value is 20
    }

Hope it helps!!