位置:首页 > 高级语言 > Objective-C在线教程 > Objective-C 传递函数的指针

Objective-C 传递函数的指针

Objective-C语言的编程语言允许传递一个指向函数的指针。要做到这一点,简单地声明一个指针类型的函数参数。

下面以一个简单的例子,我们通过一个unsigned long的函数指针和更改的函数反映在调用函数里面的值:

#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
", sec );

   return 0;
}

上面的代码编译和执行时,它会产生以下结果:

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

函数,它可以接受一个指针,也可以接受一个数组,如下面的示例中所示:

#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 yiibaier to the array as an argument */
   avg = [sampleClass getAverage: balance ofSize: 5 ] ;
 
   /* output the returned value  */
   NSLog(@"Average value is: %f
", avg );
    
   return 0;
}

当上面的代码一起编译和执行时,产生以下结果:

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