位置:首頁 > 高級語言 > 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