Objective-C 从函数返回数组

Objective-C 编程语言不允许将整个数组作为参数返回给函数。但是,您可以通过指定不带索引的数组名称来返回指向数组的指针。您将在下一章学习指针,因此可以跳过本章,直到您理解 Objective-C 中指针的概念。

如果要从函数返回一维数组,则必须声明一个返回指针的函数,如下例所示:

  1. int * myFunction() {
  2. .
  3. .
  4. .
  5. }

要记住的第二点是 Objective-C 不主张将局部变量的地址返回到函数外部,因此必须将局部变量定义为 static 静态变量。

现在,考虑下面的函数,它将生成 10 个随机数,并使用数组返回它们,然后按如下方式调用此函数:

  1. #import <Foundation/Foundation.h>
  2. @interface SampleClass:NSObject
  3. - (int *) getRandom;
  4. @end
  5. @implementation SampleClass
  6. /* function to generate and return random numbers */
  7. - (int *) getRandom {
  8. static int r[10];
  9. int i;
  10. /* set the seed */
  11. srand( (unsigned)time( NULL ) );
  12. for ( i = 0; i < 10; ++i) {
  13. r[i] = rand();
  14. NSLog( @"r[%d] = %d\n", i, r[i]);
  15. }
  16. return r;
  17. }
  18. @end
  19. /* main function to call above defined function */
  20. int main () {
  21. /* a pointer to an int */
  22. int *p;
  23. int i;
  24. SampleClass *sampleClass = [[SampleClass alloc]init];
  25. p = [sampleClass getRandom];
  26. for ( i = 0; i < 10; i++ ) {
  27. NSLog( @"*(p + %d) : %d\n", i, *(p + i));
  28. }
  29. return 0;
  30. }

结果如下:

  1. 2022-07-07 03:22:46.042 demo[5174] r[0] = 1484144440
  2. 2022-07-07 03:22:46.043 demo[5174] r[1] = 1477977650
  3. 2022-07-07 03:22:46.043 demo[5174] r[2] = 582339137
  4. 2022-07-07 03:22:46.043 demo[5174] r[3] = 1949162477
  5. 2022-07-07 03:22:46.043 demo[5174] r[4] = 182130657
  6. 2022-07-07 03:22:46.043 demo[5174] r[5] = 1969764839
  7. 2022-07-07 03:22:46.043 demo[5174] r[6] = 105257148
  8. 2022-07-07 03:22:46.043 demo[5174] r[7] = 2047958726
  9. 2022-07-07 03:22:46.043 demo[5174] r[8] = 1728142015
  10. 2022-07-07 03:22:46.043 demo[5174] r[9] = 1802605257
  11. 2022-07-07 03:22:46.043 demo[5174] *(p + 0) : 1484144440
  12. 2022-07-07 03:22:46.043 demo[5174] *(p + 1) : 1477977650
  13. 2022-07-07 03:22:46.043 demo[5174] *(p + 2) : 582339137
  14. 2022-07-07 03:22:46.043 demo[5174] *(p + 3) : 1949162477
  15. 2022-07-07 03:22:46.043 demo[5174] *(p + 4) : 182130657
  16. 2022-07-07 03:22:46.043 demo[5174] *(p + 5) : 1969764839
  17. 2022-07-07 03:22:46.043 demo[5174] *(p + 6) : 105257148
  18. 2022-07-07 03:22:46.043 demo[5174] *(p + 7) : 2047958726
  19. 2022-07-07 03:22:46.043 demo[5174] *(p + 8) : 1728142015
  20. 2022-07-07 03:22:46.043 demo[5174] *(p + 9) : 1802605257

分类导航