【问题标题】:setValue points to the object instead of copying the NSStringsetValue 指向对象而不是复制 NSString
【发布时间】:2012-09-09 15:28:44
【问题描述】:

我正在解析一个 XML 文档。我有一个 NSMutableString 来保存我通过的每个节点和特定节点的值 - 我想更新 NewsElement 类。

这是我的代码:

[newsElement setValue:currentElementValue forKey:elementName];

currentElementValue 是NSMutableString elementName 是我要更新的键。每个字段都是NSString。 问题是,现在我的 NSString 不是复制字符串,而是指向 currentElementValue 地址,因此所有字段始终相同...

【问题讨论】:

    标签: iphone xcode nsstring nsmutablestring setvalue


    【解决方案1】:

    大概复制currentElementValue 可以解决您的问题。你试过了吗:

    [newsElement setValue:[currentElementValue copy] forKey:elementName]; 
    

    这将制作currentElementValue(即NSMutableString)的不可变副本(即NSString)。如果您需要副本是可变的,您可以改用mutableCopy 方法,例如:

    [newsElement setValue:[currentElementValue mutableCopy] forKey:elementName]; 
    

    【讨论】:

    • 是的 - 成功了......任何内存命中,因为我复制整个元素而不是它的字符串值?
    • 我不知道,您没有提供足够的上下文来了解正在发生的事情。 currentElementValue 是什么,从你的问题中我认为它是 NSMutableString
    • 在这种情况下,我不确定您所说的“复制整个元素而不仅仅是其字符串值”是什么意思。 copy 方法将在那个时刻复制NSMutableString 的值。
    猜你喜欢
    • 1970-01-01
    • 2015-10-10
    • 1970-01-01
    • 1970-01-01
    • 2013-07-10
    • 1970-01-01
    • 2010-10-09
    • 1970-01-01
    • 2021-12-12
    相关资源
    最近更新 更多