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