如何在采用NSString的方法中使用NSMutableString?

时间:2013-02-09 14:47:51

标签: objective-c cocoa nsmutablestring nsscanner

NSScanner获取指向NSString的指针:

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

但myString是可变的,所以当我稍后尝试添加时会出现错误,说我试图改变一个不可变的。 我是否必须创建临时副本并返回和退出,或者是否有更有效的方法来执行此操作?

2 个答案:

答案 0 :(得分: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"];

答案 1 :(得分:1)

如果您需要多次重复,只需使用一个可变字符串:

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

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

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

//...

无需复制或进行任何其他转换。