要麼做
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"];
你的第二個例子有點有趣,因爲在[[scanner ...]行之後,你有一個帶有不可變字符串的NSMutableString變量。我認爲你的第一個更好。 – 2013-02-09 15:52:18
@JesseRusak,是的,我也這麼認爲。 – vikingosegundo 2013-02-09 15:54:27
@JesseRusak,我改變了我的答案,以更清楚地反映出來。 – vikingosegundo 2013-02-09 15:58:36