简体   繁体   中英

Assigning NSMutableString from NSString Warning

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.

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];

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM