1

NSScanner 接受一个指向 NSString 的指针:

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

但是 myString 是可变的,所以当我稍后尝试进行追加时出现错误,说我正在尝试改变一个不可改变的。我是否必须创建临时副本并来回移动,还是有更有效的方法来做到这一点?

4

2 回答 2

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"];
于 2013-02-09T15:37:49.933 回答
1

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

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

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

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

//...

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

于 2013-02-09T15:49:48.240 回答