Convert NSString separated by comma to NSArray [duplicate]

烂漫一生 提交于 2019-11-27 02:50:28

问题


Possible Duplicate:
Convert NSArray to NSString in Objective-C

I have an array of an NSArray myArray, here is the content:

 (
            "<MPConcreteMediaItem: 0x1b7dd0> 8671085923283003246",
            "<MPConcreteMediaItem: 0x1b7e50> 16275751483823231324",
            "<MPConcreteMediaItem: 0x1b7e70> 4976771456698615367"
 )

I used the code below to assign to an NSString myString:

NSString *myString = [myArray description];

And the out put is still as expected:

 (
            "<MPConcreteMediaItem: 0x1b7dd0> 8671085923283003246",
            "<MPConcreteMediaItem: 0x1b7e50> 16275751483823231324",
            "<MPConcreteMediaItem: 0x1b7e70> 4976771456698615367"
 )

Now, say I want to convert myString back to an array named newArray, I used this:

NSArray *newArray = [[NSArray alloc]init];
newArray = [myString componentsSeparatedByString:@","];

But the content of the newArray is now different:

(       
"(
    \"<MPConcreteMediaItem: 0x1b7dd0> 8671085923283003246\"",
        "
    \"<MPConcreteMediaItem: 0x1b7e50> 16275751483823231324\"",
        "
    \"<MPConcreteMediaItem: 0x1b7e70> 4976771456698615367\""
)"
) 

Any idea what I need to do to fix this?


回答1:


There are two methods

  • - (NSArray *)componentsSeparatedByString:(NSString *)separator
  • - (NSString *)componentsJoinedByString:(NSString *)separator

Use

NSString *myString = [myArray componentsJoinedByString:@","]; //instead of [myArray description];



回答2:


This is what the NSArray prints out.

"(
\"<MPConcreteMediaItem: 0x1b7dd0> 8671085923283003246\"",
    "
\"<MPConcreteMediaItem: 0x1b7e50> 16275751483823231324\"",
    "
\"<MPConcreteMediaItem: 0x1b7e70> 4976771456698615367\""
)"

To print out the individual elements in the array try this and see what happens

NSString *myString1 = [myArray objectAtIndex:1];
NSString *myString2 = [myArray objectAtIndex:2];
NSLog(myString1);
NSLog(myString2);



回答3:


Maybe I'm missing something but you are doing operations on "C" strings not NSStrings. You need more "@"s.



来源:https://stackoverflow.com/questions/8204172/convert-nsstring-separated-by-comma-to-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!