【发布时间】:2012-04-12 06:37:47
【问题描述】:
[str replaceOccurrencesOfString: withString: options: range:
[str replaceOccurrencesOfString:@"'" withString:@"!~" options:0 range:NSMakeRange(0,str.length)]
我正在使用此函数将NSMutableString 中的' 符号替换为!~ 符号,以便我可以将该字符串存储到数据库中。当我将它存储到数据库中时它工作正常,但在检索并使用相同的函数将其转换回来时,它向我显示错误。
错误
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Attempt to mutate immutable object with replaceOccurrencesOfString:withString:options:range:'
这里,str 是 NSMutableString 类型。我检查了它的类型[str class] 它转换为NSCFString 不知道为什么它会改变?我也尝试将其转换为NSMutableString,但它没有转换。我以其他方式尝试了很多次,但它在所有其他地方都可以正常工作,仅在我的一个视图控制器中,它向我展示了这一点。
你猜我哪里做错了吗?
【问题讨论】:
-
在使用前尝试分配str变量。
-
@RamaRao,我试过了!它不工作。
-
你试过这样 NSString *str = [[[NSString alloc] init] retain];
-
您如何在代码中声明和设置
str?字符串中的文本来自哪里(代码的其他部分),那么它是可变的吗? -
[str isKindOfClass:[NSMutableString class]],检查这个语句是否返回真,我怀疑这个问题只是由于不可变。
标签: iphone replace nsmutablestring nscfstring