Tuesday, January 12, 2016

Objective C NSString to NSArray & NSArray to NSString conversions

Let's start with discussing a scenario where we need to convert NSArray to NSString.

We have an array of tags for a particular file or folder any CMS. We need to display them comma (,) separated in our application. For this, one approach is to loop through all the array items and adding them to a mutable string with comma separator like shown below.


NSArray *arr = [NSArray alloc] initWithObjects:@"last year",@"favorite",@"high quality",nil];

Let's say this is my array having all the tags of one of user's albums. I want to display them below the albums folder comma separated. If we want to do the complex approach, It will be like shown below.

First we need to take a mutable string.

NSMutableString *str = [NSMutableString alloc] init];

We need to iterate through all the items in the array.

for(int i=0;

      NSString *tag = (NSString*)[arr objectAtIndex:i];
      [str appendString:tag];

      if(i != (arr.count-1)){

           //adding comma separator excluding the last element.
           [str appendString:@", "]; 


NSLog(@"%@",str);     =>   last year, favorite, high quality

Isn't it a complex process for a simple logic?

To make it simple, we have a native inbuilt function in the NSArray. Here it is.

NSString *str = [arr componentsJoinedByString:@", "];

NSLog(@"%@",str);     =>   last year, favorite, high quality

So simple right. Just a line of statement to convert our array to string with our required separator.

Now, let's see the reverse process, that means I want to convert that tags string to a list of array to do some actions like to add or remove an item. For this also, don't go for a complex process. We have an in built function in NSString to convert into an NSArray. Here it is

NSArray *arr = [str componentsSeparatedByString:@", "];

Very simple and just a single line of statement to convert array to string or string to an array If we go for built in functions. 


Hope this post is helpful. Feel free to comment incase of any queries.