Waqar
Waqar

Reputation: 105

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?

Upvotes: 6

Views: 7132

Answers (3)

Chris Cooper
Chris Cooper

Reputation: 17564

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.

Upvotes: 7

huskerchad
huskerchad

Reputation: 1037

C-style arrays are not NSArray's so your assignment of arry (the definition of which has some typos, at least the unsighned part) is not valid. In addition, you call arry an array of char, but you assign it an array of null-terminated strings.

In general you need to loop and add all the elements of the C-style array to the NSArray.

Upvotes: 1

futureelite7
futureelite7

Reputation: 11502

I'm not sure why you must do it in main. If you want a global you can do it by declaring a global in another file. That said, you CANNOT assign a plain C data array to an objective C NSArray, which is different in nature entirely.

Upvotes: 0

Related Questions