Objective-C 函数返回数组

  • 函数返回数组

    Objective-C编程语言不允许将整个数组作为函数的参数返回。但是,您可以通过指定不带索引的数组名称来返回指向数组的指针。您将在后面章学习指针,因此可以跳过本章,直到您了解Objective-C中的指针的概念。如果要从函数返回一维数组,则必须声明一个返回指针的函数,如以下示例所示:
    
    int * myFunction() {
    .
    .
    .
    }
    
    要记住的第二点是,Objective-C不主张将局部变量的地址返回到函数外部,因此您必须将局部变量定义为静态变量。现在,考虑以下函数,它将生成10个随机数,并使用数组返回它们,并按如下所示调用此函数-
  • 示例

    
    #import <Foundation/Foundation.h>
    
    @interface SampleClass:NSObject
    - (int *) getRandom;
    @end
    
    @implementation SampleClass
    
    /* function to generate and return random numbers */
    - (int *) getRandom {
       static int  r[10];
       int i;
    
       /* set the seed */
       srand( (unsigned)time( NULL ) );
       for ( i = 0; i < 10; ++i) {
          r[i] = rand();
          NSLog( @"r[%d] = %d\n", i, r[i]);
       }
    
       return r;
    }
    
    @end
    
    /* main function to call above defined function */
    int main () {
       
       /* a pointer to an int */
       int *p;
       int i;
    
       SampleClass *sampleClass = [[SampleClass alloc]init];
       p = [sampleClass getRandom];
       for ( i = 0; i < 10; i++ ) {
          NSLog( @"*(p + %d) : %d\n", i, *(p + i));
       }
    
       return 0;
    }
    
    当以上代码一起编译并执行时,将产生以下结果-
    
    2020-08-07 09:12:24.094 test[12592:13452] r[0] = 16208
    2020-08-07 09:12:24.099 test[12592:13452] r[1] = 8730
    2020-08-07 09:12:24.099 test[12592:13452] r[2] = 31821
    2020-08-07 09:12:24.099 test[12592:13452] r[3] = 372
    2020-08-07 09:12:24.099 test[12592:13452] r[4] = 9326
    2020-08-07 09:12:24.099 test[12592:13452] r[5] = 6941
    2020-08-07 09:12:24.099 test[12592:13452] r[6] = 29547
    2020-08-07 09:12:24.099 test[12592:13452] r[7] = 25573
    2020-08-07 09:12:24.099 test[12592:13452] r[8] = 23286
    2020-08-07 09:12:24.099 test[12592:13452] r[9] = 15924
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 0) : 16208
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 1) : 8730
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 2) : 31821
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 3) : 372
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 4) : 9326
    2020-08-07 09:12:24.099 test[12592:13452] *(p + 5) : 6941
    2020-08-07 09:12:24.100 test[12592:13452] *(p + 6) : 29547
    2020-08-07 09:12:24.100 test[12592:13452] *(p + 7) : 25573
    2020-08-07 09:12:24.100 test[12592:13452] *(p + 8) : 23286
    2020-08-07 09:12:24.100 test[12592:13452] *(p + 9) : 15924