简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM