Pregunta

I have the following three lines of code in my program:

NSMutableString *stringOne = [NSMutableString stringWithFormat:@"Hello "];
NSMutableString *stringTwo = [NSMutableString stringWithFormat:@"World"];
NSMutableString *sayIt = [stringOne stringByAppendingString:stringTwo];

Despite the fact that it works, the third line is causing the warning Assigning NSMutableString * from NSString *.

I am at a loss here since everything I am using is an NSMutableString.

¿Fue útil?

Solución

Not quite. stringByAppendingString does not return an NSMutableString. Instead do the following:

NSMutableString *sayIt = [NSMutableString stringWithString:stringOne];
[sayIt appendString:stringTwo];

Or

NSMutableString *sayIt = [[stringOne stringByAppendingString:stringTwo] mutableCopy];

Otros consejos

I just realized that stringByAppendingString: returns an NSString despite calling it from an NSMutableString object. Since I am dealing with NSMutableString, I should have used that class's appendString: method. The new code that works without a warning is:

NSMutableString *stringOne = [NSMutableString stringWithFormat:@"Hello "];
NSMutableString *stringTwo = [NSMutableString stringWithFormat:@"World"];
[stringOne appendString:stringTwo];
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top