ilteris
ilteris

Reputation: 457

Appending to NSMutableString in a for loop

NSMutableString*  highlightedString = [NSMutableString stringWithCapacity:1];
for (QWZTerm* term in self.highlightArray) {
    [highlightedString stringByAppendingFormat:@"%@ ", term.value];
}

Basically term.values are NSStrings ( "john" and "mary" and I would like to append them like "john mary". Unfortunately above doesn't work for me. I would appreciate any directions.

Upvotes: 2

Views: 852

Answers (4)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726479

You are using a wrong method: stringByAppendingFormat: works on all strings, mutable and immutable, because it returns a new NSString object.

Since you are looking to change the content of mutable highlightedString itself, you need to use appendFormat: instead:

NSMutableString*  highlightedString = [NSMutableString stringWithCapacity:1];
for (QWZTerm* term in self.highlightArray) {
    [highlightedString appendFormat:@"%@ ", term.value];
}

You could do the whole thing without using mutable strings or loops, in a single line of code:

NSString* res = [[highlightArray valueForKey:@"value"] componentsJoinedByString:@" "];

The "magic" behind the valueForKey call is described here.

Upvotes: 5

hariszaman
hariszaman

Reputation: 8424

you can also change the line

[highlightedString stringByAppendingFormat:@"%@ ", term.value];

to

highLightedString = [highlightedString stringByAppendingFormat:@"%@ ", term.value];

Upvotes: 0

DarkDust
DarkDust

Reputation: 92306

A different solution would be to gather the strings in a mutable array and then join them:

NSMutableArray* values = [NSMutableArray array];
for (QWZTerm* term in self.highlightArray) {
    [values addObject:term.value];
}

NSString* highlightedString = [values componentsJoinedByString:@" "];

This avoids the trailing space you'll get with the appenFormat: solution.

Upvotes: 2

rakeshbs
rakeshbs

Reputation: 24572

Your function is wrong. Use appendFormat:. stringByAppendingFormat: returns a new NSString object and does not append to there NSMutableString instance.

NSMutableString*  highlightedString = [NSMutableString stringWithCapacity:1];
for (QWZTerm* term in self.highlightArray) {
    [highlightedString appendFormat:@"%@ ", term.value];
}

Upvotes: 1

Related Questions