How to convert NSArray into NSString

2020-02-09 05:15发布

问题:

How to convert NSArray into NSString in objective-c?

回答1:

Bearing in mind that you don't say what's in the NSArray, you can do this:

NSArray *arr = [NSArray arrayWithObjects: @"foo", @"bar", @"baz"];
[arr componentsJoinedByString: @","]


回答2:

Aternatively to Frank's method, which works pretty well, you could also do

NSString *myArrayString = [array description];

The default implementation of description on NSArray will print out the contents in a neatly formatted fashion.



回答3:

This is how I have converted my NSArray to NSString

NSError *error = nil;

NSData *data = [NSJSONSerialization dataWithJSONObject:aArray options:kNilOptions error:&error];

NSString *str = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];


回答4:

Swift 3.0 latest updates

let string = array.componentsJoined(by: ",")

you can used any separator in function which you want to separate the array elements currently in above example is ",".