之后的属性在后续调用

时间:2018-01-15 01:14:37

标签: ios swift swift4 nsattributedstring

我遇到了一个奇怪的场景,其中我的扩展方法生成的先前属性(属于属性字符串的自定义属性)也在后续调用中分配。它的行为就像一个静态值被缓存并在我调用它的任何地方分配它。

extension Model {
    func attributedString() -> NSAttributedString {

        // Generate an icon, represented by the type of model
        let icon = ...

        // Merge both icon and the value of the ziptag
        let preferredAttributedString = NSMutableAttributedString(attributedString: icon.attributedString())
        let attributedValue = NSAttributedString(string: self.value)
        preferredAttributedString.append(attributedValue)

        // Mention Attribute
        let mentionAttributeKey = NSAttributedStringKey(HKWMentionAttributeName)
        guard let mentionAttribute = HKWMentionsAttribute.mention(withText: self.value, identifier: self.id) else {
            fatalError("mentionAttribute can't be nil")
        }
        mentionAttribute.metadata = self.entityMetadata()

        // Color Attribute
        let foregroundColor = UIColor.blue

        // Set the attributes
        let attributes: [NSAttributedStringKey : Any] = [mentionAttributeKey : mentionAttribute,
                                                     NSAttributedStringKey.foregroundColor : foregroundColor]

        preferredAttributedString.addAttributes(attributes, range: preferredAttributedString.range)

        return preferredAttributedString
    }
}

这就是我复制它的方式。假设我有两个类型为model的对象,它们具有在上面声明和实现的扩展方法。

let modelA = Model()
let modelB = Model()
let attributedStringA = modelA.attributedString()
let attributedStringB = modelB.attributedString()

我已经记录了上面的两个属性字符串,我希望它分别显示modelAmodelB属性,但它只会在两个属性字符串上生成modelA

添加有关问题的更多数据。上面生成的图标是自定义字体FontAwesome,它还会生成一个属性字符串,并添加到Model的属性字符串(使用系统的字体)。

我在生成所需属性的语句上运行 Xcode的lldb ,并且报告正确;但是一旦我在属性字符串上分配了属性,就会出现上述问题

1 个答案:

答案 0 :(得分:0)

我通过在我的问题上的代码段添加未使用的自定义属性来修复它

// Mention Attribute
let mentionAttributeKey = NSAttributedKey(HKWMentionAttributeName)
let mentionAttribute = ....

// Foreground Color
let foregroundColor = UIColor.blue

// Trash Attribute
let trashAttributeKey = NSAttributedKey("TrashAttribute")
let trashAttribute = Trash()

添加垃圾属性后,它现在可以完美运行;因为此扩展方法之前没有更多延迟属性,特别是在归属字符串的 Icon 部分

相关问题