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 ", i, r[i]); } return r; } @end /* main function to call above defined function */ int main () { /* a yiibaier 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 ", i, *(p + i)); } return 0; }
当上面的代码一起编译和执行时,它产生的结果如下:
2013-09-14 03:22:46.042 demo[5174] r[0] = 1484144440 2013-09-14 03:22:46.043 demo[5174] r[1] = 1477977650 2013-09-14 03:22:46.043 demo[5174] r[2] = 582339137 2013-09-14 03:22:46.043 demo[5174] r[3] = 1949162477 2013-09-14 03:22:46.043 demo[5174] r[4] = 182130657 2013-09-14 03:22:46.043 demo[5174] r[5] = 1969764839 2013-09-14 03:22:46.043 demo[5174] r[6] = 105257148 2013-09-14 03:22:46.043 demo[5174] r[7] = 2047958726 2013-09-14 03:22:46.043 demo[5174] r[8] = 1728142015 2013-09-14 03:22:46.043 demo[5174] r[9] = 1802605257 2013-09-14 03:22:46.043 demo[5174] *(p + 0) : 1484144440 2013-09-14 03:22:46.043 demo[5174] *(p + 1) : 1477977650 2013-09-14 03:22:46.043 demo[5174] *(p + 2) : 582339137 2013-09-14 03:22:46.043 demo[5174] *(p + 3) : 1949162477 2013-09-14 03:22:46.043 demo[5174] *(p + 4) : 182130657 2013-09-14 03:22:46.043 demo[5174] *(p + 5) : 1969764839 2013-09-14 03:22:46.043 demo[5174] *(p + 6) : 105257148 2013-09-14 03:22:46.043 demo[5174] *(p + 7) : 2047958726 2013-09-14 03:22:46.043 demo[5174] *(p + 8) : 1728142015 2013-09-14 03:22:46.043 demo[5174] *(p + 9) : 1802605257