42

So I have no experience with arrays... But I need to use one to populate a UIPickerView. I am obtaining a list of objects via HTTP (NSURLConnection). This works fine. Currently, the response is stored in a NSString as a comma-separated list. I need to convert it to an array. I think this is the type of array I need:

NSArray  * myArray2 = [NSArray arrayWithObjects:@"foo",@"bar",@"baz",nil];

Maybe I'm overcomplicating things... I'm really not sure. There is already an array for the PickerView, and I have it setup so to add an item to the PickerView array I use this code:

[pickerArray addObject:@"Item 1"];

So... How do I separate the items in a comma-separated string (item 1,item 2,item 3,...) into separate array items ([pickerArray addObject:@"item 1"];)??

whitebreadb
  • 525
  • 2
  • 6
  • 6

2 Answers2

141

Assuming there's no worry about escaping/unescaping commas contained within the strings, it should be this simple:

NSArray *items = [theString componentsSeparatedByString:@","];
Andrew Madsen
  • 21,309
  • 5
  • 56
  • 97
  • So that code will create an array from the comma-separated string? – whitebreadb Jan 29 '12 at 23:11
  • Yes, as explained in the documentation for NSString: http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSString_Class/Reference/NSString.html – Andrew Madsen Jan 29 '12 at 23:14
  • It's late atm and I forgot about this method, it always makes me wonder why some answers aren't chosen as the correct answer. – Rick van der Linde Feb 12 '13 at 22:09
  • @RickvanderLinde I think especially with inexperienced StackOverflow users, they just don't know or forget that they should accept an answer to their question. Oh well... – Andrew Madsen Feb 12 '13 at 23:35
  • How would I take a comma separated value NSString = "15.009483, -87.485195" and separate them into coordinate values to plot? – marciokoko Apr 23 '13 at 21:20
  • @marciokoko, you should ask a new question about that. – Andrew Madsen Apr 23 '13 at 22:21
0

Objective-C

NSString *list = @"Karin, Carrie, David";
NSArray *listItems = [list componentsSeparatedByString:@", "];