andrewz
andrewz

Reputation: 5220

How to convert NSArray into NSString**

I have an NSArray that contains objects of NSString. I want to create an NSString ** object from those strings.

NSArray * myArray = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSString ** myStrings = ??? // an array of NSString*

Is there a non-malloc solution? Can we allocate myStrings in the autorelease pool somehow, or obtain a handle to the objects property in myArray and use that?

Upvotes: 1

Views: 613

Answers (1)

bacongravy
bacongravy

Reputation: 923

DISCLAIMER: You shouldn't do this.

That said, here is how you can create a C array of NSString pointers from an NSArray, backed by autoreleased memory:

NSArray * myArray = [NSArray arrayWithObjects:@"a",@"b",@"c",nil];
NSMutableData * myData = [NSMutableData dataWithLength:(sizeof(NSString *) * myArray.count)];    
NSString ** myStrings = myData.mutableBytes;
for (int i = 0; i < myArray.count; i++) {
    myStrings[i] = myArray[i];
}

This is a terrible idea, from a memory management perspective.

Each myStrings[i] value will only be valid for so long as myArray is retained, and the value of myStrings will only be valid for so long as myData is retained.

Under ARC, the myArray and myData objects will be released as soon as they go out of scope, so myStrings will point to free'd memory as soon as it is returned from a method.

Upvotes: 3

Related Questions