Your problem is that you dont clean the string each time, and so you append data to the previous code. In any case, i write the best code for you because your is a little bit redundant:
colorsString = @"";
for(int i = 0 ; i <colorsArray.count ; i++)
{
TheColor * color1 = [colorsArray objectAtIndex:i];
if([color1.isSelected isEqualToString: @"YES"])
{
colorsString = [colorsString stringByAppendingFormat:@"%@%@", ([colorsString isEqualToString:@""]) ? @"" : @",", color1.colorName];
NSLog(@"Color name %@",colorsString);
}
}
But we can optimize the code again: if the color selected is EACH TIME 1, and so you haven't multiple selected color, you can exit from the for cycle when you find that color:
colorsString = @"";
for(int i = 0 ; i <colorsArray.count ; i++)
{
TheColor * color1 = [colorsArray objectAtIndex:i];
if([color1.isSelected isEqualToString: @"YES"])
{
colorsString = [colorsString stringByAppendingFormat:@"%@%@", ([colorsString isEqualToString:@""]) ? @"" : @",", color1.colorName];
NSLog(@"Color name %@",colorsString);
break;
}
}
Another thing: THIS: [color1.isSelected isEqualToString: @"YES"]
...tell me WHY?
You must have a BOOL
@property
in your TheColor
class and not a string. So replace the property with this:
@property (assign, getter=isSelected) BOOL selected;
Then in your code you can simply do:
if(color1.isSelected)
and so here the final code:
colorsString = @"";
for(int i = 0 ; i <colorsArray.count ; i++)
{
TheColor * color1 = [colorsArray objectAtIndex:i];
if(color1.isSelected)
{
colorsString = [colorsString stringByAppendingFormat:@"%@%@", ([colorsString isEqualToString:@""]) ? @"" : @",", color1.colorName];
NSLog(@"Color name %@",colorsString);
break;
}
}