Reputation: 3858
I am trying to create a String from Array.But, there is condition to how it should be generated, as explained below.
NSArray *array=[NSArray arrayWithObjects:@"Hello",@"World",nil];
[array componentsJoinedByString:@","];
This will output: Hello,World.
But, if first Item is Empty,then is there way to receive the only second one.
Upvotes: 5
Views: 5825
Reputation: 35706
Another way to do this is to grab a mutable copy of the array and just remove non valid objects. Something like this perhaps:
NSMutableArray *array = [[NSArray arrayWithObjects:@"",@"World",nil] mutableCopy];
[array removeObject:@""]; // Remove empty strings
[array removeObject:[NSNull null]]; // Or nulls maybe
NSLog(@"%@", [array componentsJoinedByString:@","]);
Upvotes: 13
Reputation: 727077
You cannot store nil
values in NSArray
*, so the answer is "no". You need to iterate the array yourself, keeping track of whether you need to add a comma or not.
NSMutableString *res = [NSMutableString string];
BOOL first = YES;
for(id item in array) {
if (id == [NSNull null]) continue;
// You can optionally check for item to be an empty string here
if (!first) {
[res appendString:@", "];
} else {
first = NO;
}
[res appendFormat:@"%@", item];
}
nil
values in NS collections are represented with NSNull
objects.
Upvotes: 4