要么做
NSString *myString; //this is just a variable identifier, no object was created and assigned to it yet
...
//scanner will create a NSString and write it to myString. It won't know it is passed to a variable typed NSMutableString or NSString
[scanner scanUpToCharactersFromSet:charSet intoString:&myString];
//instead of creating mutable string you can create a new immutable by appending a string
myString = [myString stringByAppendingString:@"hello"];
或更好:查看下一个代码片段
NSMutableString *myString; //this is just a variable identifier, no object was created and assigned to it yet
...
//scanner will create a NSString and write it to myString. It won't know it is passed to a variable typed NSMutableString
[scanner scanUpToCharactersFromSet:charSet intoString:&myString];
//myString contains a NSString now, not NSMutableString
myString = [myString mutableCopy]; // make a mutable copy and assign it to the variable
[myString appendString:@"hello"];
在第二种方法中,您将在短时间内不一致 NSMutable 类型变量将保存不可变字符串。这绝对是一个缺陷。解决方案一更清洁。如果你喜欢两个,你应该引入第二个 NSString 变量并将其传递给扫描仪,然后将它的可变副本传递给你的 NSMutableString。
NSString *tempString;
NSMutableString *myString;
...
[scanner scanUpToCharactersFromSet:charSet intoString:&tempString];
myString = [tempString mutableCopy];
[myString appendString:@"hello"];