代码之家  ›  专栏  ›  技术社区  ›  Chi Long Qua

在后续调用中传播的以前的属性

  •  0
  • Chi Long Qua  · 技术社区  · 7 年前

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

    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()
    

    我已经记录了上面的两个属性字符串,我希望它会出现 modelA modelB 属性,但它只生成 模型A 在两个属性化字符串上

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

    我已经跑了 Xcode的lldb 关于产生所需属性的语句及其报告权;但一旦我在属性字符串上指定了属性,就会出现上述问题

    1 回复  |  直到 7 年前
        1
  •  0
  •   Chi Long Qua    7 年前

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

    // Mention Attribute
    let mentionAttributeKey = NSAttributedKey(HKWMentionAttributeName)
    let mentionAttribute = ....
    
    // Foreground Color
    let foregroundColor = UIColor.blue
    
    // Trash Attribute
    let trashAttributeKey = NSAttributedKey("TrashAttribute")
    let trashAttribute = Trash()
    

    添加垃圾属性后,它现在可以正常工作;因为之前在 偶像 属性字符串的一部分