How to pass values ​​by reference in object C (iphone)

I have a very simple question. I am a new iPhone programmer. My question is can someone tell me how I can pass values ​​by reference to a function in obj. C? I know how to do this in VB and C #. But I do not know how to do this in Obj c.

thank

+41
objective-c
Aug 28 '09 at 0:43
source share
6 answers

Passing by reference in Objective-C is the same as passing in C.

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 an

 - (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); 
+88
Aug 28 '09 at 1:22
source share

Objective C. does not pass by reference (in the sense of C ++). You can pass your objects with a pointer to primitive types by value.

Example:

 void func(NSString* string) { ... } void func(NSInteger myint) { ... } .. NSString* str = @"whatever"; NSInteger num = 5; func(str); func(num); 
+13
Aug 28 '09 at 0:44
source share

If you use Objective C ++, which you can do by naming your file with the extension .mm or by telling Xcode to compile all the source code as Objective C ++, you can pass links the same way as with C ++, for example:

 - (OSStatus) fileFileInfo: (FileInfo&)fi; 
+13
Aug 28 '09 at 1:26
source share

Try as follows:

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

Hope this helps!

+7
Nov 22
source share

It depends on what you mean. The closest thing to C (and therefore Objective-C) is the reference type - pointers. As the name implies, pointers point to data that exists elsewhere. To get an indication of what you need, you must dereference the pointer. Objects in Objective-C are never directly accessible - you always use pointers to talk to them. You can also pass pointers to types other than objects.

Pointers are a tricky question. I definitely recommend reading in C to get a feel for them.

0
Aug 28 '09 at 0:57
source share

There must be an argument if you want to get more than one address from the resulting function call. You can do this instead by creating a wrapper class and passing it instead. For example:

 @interface AddressWrapper : NSObject { NSArray *array; NSString *string; } @property (nonatomic, assign) NSArray *array; @property (nonatomic, assign) NSString *string; @end 

In * .m:

 @implementation AddressWrapper @synthesize array, string; @end -(void) getAddresses: (AddressWrapper*) wrapper { wrapper.array = myNSArray; wrapper.string = myNSString; } 
0
Apr 13 2018-12-12T00:
source share



All Articles