我遇到了一个奇怪的场景,其中由我的扩展方法生成的先前属性(这是属性字符串的自定义属性)也在后续调用中分配。它的行为就像一个静态值被缓存并在我调用它的任何地方分配它。
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
属性,但它只生成 modelA
> 在两个属性字符串上
添加有关该问题的更多数据。上面生成的图标是自定义字体 FontAwesome它还将生成一个属性字符串,并添加到模型的属性字符串前面(使用系统的字体)。
我已经在生成所需属性的语句上运行了Xcode 的 lldb,并且报告正确;但是一旦我在属性字符串上分配了属性,上述问题就开始出现
最佳答案
我通过在我的问题的代码片段上添加未使用的自定义属性来修复它
// Mention Attribute
let mentionAttributeKey = NSAttributedKey(HKWMentionAttributeName)
let mentionAttribute = ....
// Foreground Color
let foregroundColor = UIColor.blue
// Trash Attribute
let trashAttributeKey = NSAttributedKey("TrashAttribute")
let trashAttribute = Trash()
添加trash属性后,现在可以完美运行了;因为此扩展方法之前不再专门在属性字符串的 Icon 部分创建任何挥之不去的属性
关于ios - 先前的属性在后续调用中传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255821/