Iphone 设置值指向对象,而不是复制NSString
我正在解析一个XML文档。我有一个Iphone 设置值指向对象,而不是复制NSString,iphone,xcode,nsstring,nsmutablestring,setvalue,Iphone,Xcode,Nsstring,Nsmutablestring,Setvalue,我正在解析一个XML文档。我有一个NSMutableString来保存我要通过的每个节点和特定节点的值-我想更新newsement类 这是我的代码: [newsElement setValue:currentElementValue forKey:elementName]; currentElementValue是NSMutableString元素名是我要更新的键。每个字段都是NSString。 问题是,现在我的NSString指向currentElementValue地址,而不是复制字符串,
NSMutableString
来保存我要通过的每个节点和特定节点的值-我想更新newsement
类
这是我的代码:
[newsElement setValue:currentElementValue forKey:elementName];
currentElementValue是NSMutableString
元素名是我要更新的键。每个字段都是NSString
。
问题是,现在我的
NSString
指向currentElementValue地址,而不是复制字符串,因此所有字段总是相同的…复制currentElementValue
可能会解决问题。您是否尝试过:
[newsElement setValue:[currentElementValue copy] forKey:elementName];
这将生成currentElementValue
的不可变副本(即NSString
),该值为NSMutableString
。如果您需要副本是可变的,您可以使用mutableCopy
方法,例如:
[newsElement setValue:[currentElementValue mutableCopy] forKey:elementName];
是的-这就成功了。。。因为我复制了整个元素而不仅仅是它的字符串值,所以内存有问题吗?我不知道,您没有提供足够的上下文来知道发生了什么。什么是
currentElementValue
,从您的问题中,我假设它是一个NSMutableString
?在这种情况下,我不确定您所说的“复制整个元素而不仅仅是它的字符串值”是什么意思。copy
方法将在此时复制NSMutableString
的值。