Question

I want to append multiple strings together in a loop but it keeps on adding the same data more than once.

for(int i = 0 ; i <colorsArray.count ; i++)
{
    TheColor * color1 = [colorsArray objectAtIndex:i];
    if([color1.isSelected isEqualToString: @"YES"])
    {
        if ([colorsString isEqualToString:@""])
        {
            colorsString = color1.colorName;
        }
        else
        {
            colorsString =   [colorsString stringByAppendingFormat:@",%@",color1.colorName];
            NSLog(@"Color name %@",colorsString);
        }
    }
}

The result 1st time : red The result 2nd time : red , red , yellow The result 3rf time : red , red , yellow , purple

Was it helpful?

Solution

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;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top