9

How to convert NSArray into NSString in objective-c?

Sam Spencer
  • 8,492
  • 12
  • 76
  • 133
Arun K Sharma
  • 294
  • 1
  • 6
  • 17

4 Answers4

29

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: @","]
Frank Shearar
  • 17,012
  • 8
  • 67
  • 94
  • Yes, I find that this is strongly assuming that you are having text. Or is it using description field instead? Most likely... But barely usable in that context. – nembleton Oct 01 '12 at 21:26
12

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.

Jasarien
  • 58,279
  • 31
  • 157
  • 188
  • 1
    one problem here is that myArrayString will have {} around the text...how to get rid of this? thanks! – TommyG Nov 04 '11 at 23:26
4

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];
Radim Köhler
  • 122,561
  • 47
  • 239
  • 335
TheGreen
  • 41
  • 2
1

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 ",".

Sai Apps
  • 3
  • 1
Chavda jaydeep
  • 332
  • 3
  • 9