Return array from function in Objective-C



Objective-C programming language does not allow to return an entire array as an argument to a function. However, you can return a pointer to an array by specifying the array's name without an index. You will study pointer in next chapter so you can skip this chapter until you understand the concept of Pointers in Objective-C.

If you want to return a single-dimensional array from a function, you would have to declare a function returning a pointer as in the following example −

int * myFunction() {
.
.
.
}

Second point to remember is that Objective-C does not advocate to return the address of a local variable to outside of the function so you would have to define the local variable as static variable.

Now, consider the following function, which will generate 10 random numbers and return them using an array and call this function as follows −

#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;
}

When the above code is compiled together and executed, it produces result something as follows −

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
objective_c_arrays.htm
Advertisements