Objective-C 将指针传递给函数

Objective-C 编程语言允许您传递指向函数的指针。为此,只需将函数参数声明为指针类型。

下面是一个简单的例子,我们将一个无符号长指针传递给一个函数,并更改函数内部的值,该值反映在调用函数中:

  1. #import <Foundation/Foundation.h>
  2. @interface SampleClass:NSObject
  3. - (void) getSeconds:(int *)par;
  4. @end
  5. @implementation SampleClass
  6. - (void) getSeconds:(int *)par {
  7. /* get the current number of seconds */
  8. *par = time( NULL );
  9. return;
  10. }
  11. @end
  12. int main () {
  13. int sec;
  14. SampleClass *sampleClass = [[SampleClass alloc]init];
  15. [sampleClass getSeconds:&sec];
  16. /* print the actual value */
  17. NSLog(@"Number of seconds: %d\n", sec );
  18. return 0;
  19. }

结果如下:

  1. 2022-07-07 23:50:47.572 demo[319] Number of seconds: 1379141447

该函数可以接受指针,也可以接受数组,如下例所示:

  1. #import <Foundation/Foundation.h>
  2. @interface SampleClass:NSObject
  3. /* function declaration */
  4. - (double) getAverage:(int *)arr ofSize:(int) size;
  5. @end
  6. @implementation SampleClass
  7. - (double) getAverage:(int *)arr ofSize:(int) size {
  8. int i, sum = 0;
  9. double avg;
  10. for (i = 0; i < size; ++i) {
  11. sum += arr[i];
  12. }
  13. avg = (double)sum / size;
  14. return avg;
  15. }
  16. @end
  17. int main () {
  18. /* an int array with 5 elements */
  19. int balance[5] = {1000, 2, 3, 17, 50};
  20. double avg;
  21. SampleClass *sampleClass = [[SampleClass alloc]init];
  22. /* pass pointer to the array as an argument */
  23. avg = [sampleClass getAverage: balance ofSize: 5 ] ;
  24. /* output the returned value */
  25. NSLog(@"Average value is: %f\n", avg );
  26. return 0;
  27. }

结果如下:

  1. 2022-07-07 00:02:21.910 demo[9641] Average value is: 214.400000

分类导航