Passing Pointers to Functions in Objective-C



Objective-C programming language allows you to pass a pointer to a function. To do so, simply declare the function parameter as a pointer type.

Following a simple example where we pass an unsigned long pointer to a function and change the value inside the function which reflects back in the calling function −

#import <Foundation/Foundation.h>
 
@interface SampleClass:NSObject
- (void) getSeconds:(int *)par;
@end

@implementation SampleClass

- (void) getSeconds:(int *)par {
 /* get the current number of seconds */
   *par = time( NULL );
   return;
}

@end

int main () {
   int sec;

   SampleClass *sampleClass = [[SampleClass alloc]init];
   [sampleClass getSeconds:&sec];

   /* print the actual value */
   NSLog(@"Number of seconds: %d\n", sec );

   return 0;
}

When the above code is compiled and executed, it produces the following result −

2013-09-13 23:50:47.572 demo[319] Number of seconds: 1379141447

The function, which can accept a pointer, can also accept an array as shown in the following example −

#import <Foundation/Foundation.h>
 
@interface SampleClass:NSObject
/* function declaration */
- (double) getAverage:(int *)arr ofSize:(int) size;
@end

@implementation SampleClass

- (double) getAverage:(int *)arr ofSize:(int) size {
   int    i, sum = 0;       
   double avg;

   for (i = 0; i < size; ++i) {
      sum += arr[i];
   }

   avg = (double)sum / size;
   return avg;
}

@end

int main () {

   /* an int array with 5 elements */
   int balance[5] = {1000, 2, 3, 17, 50};
   double avg;

   SampleClass *sampleClass = [[SampleClass alloc]init];
   /* pass pointer to the array as an argument */
   avg = [sampleClass getAverage: balance ofSize: 5 ] ;

   /* output the returned value  */
   NSLog(@"Average value is: %f\n", avg );

   return 0;
}

When the above code is compiled together and executed, it produces the following result −

2013-09-14 00:02:21.910 demo[9641] Average value is: 214.400000
objective_c_pointers.htm
Advertisements