2013-02-09 40 views
1

NSScanner採用指向一個NSString:如何在使用NSString的方法中使用NSMutableString?

NSMutableString *myString; 
... 
[scanner scanUpToCharactersFromSet:charSet intoString:&myString]; 
[myString appendString:@"hello"]; 

但MyString的是可變的,所以我得到一個錯誤,當我嘗試做以後追加,說我試圖變異的未mutatable。 我必須創建臨時副本並返回&,還是有更有效的方法來執行此操作?

回答

3

要麼做

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"]; 
+0

你的第二個例子有點有趣,因爲在[[scanner ...]行之後,你有一個帶有不可變字符串的NSMutableString變量。我認爲你的第一個更好。 – 2013-02-09 15:52:18

+0

@JesseRusak,是的,我也這麼認爲。 – vikingosegundo 2013-02-09 15:54:27

+0

@JesseRusak,我改變了我的答案,以更清楚地反映出來。 – vikingosegundo 2013-02-09 15:58:36

1

如果您需要重複即多次,只有一個可變的字符串做:

NSMutableString *mutableString = [NSMutableString string]; 
NSString *string = nil; 

[scanner scanUpToCharactersFromSet:charSet1 intoString:&string]; 
[mutableString appendString:string]; 

[scanner scanUpToCharactersFromSet:charSet2 intoString:&string]; 
[mutableString appendString:string]; 

//... 

無需將它們複製或做其他任何轉換。

相關問題