Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert a c-style char* array to NSArray?

a.H:

-(NSArray *) returnarray:(int) aa
{
  unsigned char arry[1000]={"aa","vv","cc","cc","dd"......};
  NSArray *tmpary=arry;
  return tmpary;
}

a.c:

#include "a.H"
main (){
  // how do I call returnarray function to get that array in main class
}

I need that array in main and I need to retain that array function in separate class.

Can someone please provide a code example to do this?

like image 221
Waqar Avatar asked Jan 03 '12 05:01

Waqar


1 Answers

These lines:

unsigned char arry[1000]={"aa", "vv", "cc", "cc", "dd", ...};
NSArray *tmpary=arry;

Should instead be:

unsigned char arry[1000]={"aa", "vv", "cc", "cc", "dd", ...};
NSMutableArray * tmpary = [[NSMutableArray alloc] initWithCapacity: 1000];
for (i = 0; i < 1000; i++)
{
    [tmpary addObject: [NSString stringWithCString: arry[i] encoding:NSASCIIStringEncoding]];
}

This is because a C-style array (that is, int arr[10]; for example) are not the same as actual NSArray objects, which are declared as above.

In fact, one has no idea what an NSArray actually is, other than what the methods available to you are, as defined in the documentation. This is in contrast to the C-style array, which you are guaranteed is just a contiguous chunk of memory just for you, big enough to hold the number of elements you requested.

like image 157
Chris Cooper Avatar answered Sep 19 '22 02:09

Chris Cooper