我遇到了一个奇怪的场景,在后续的调用中还分配了我的扩展方法生成的先前属性(这是属性字符串的自定义属性)。它的行为就像静态值被缓存并在我调用它的任何地方分配给它。
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
}
}
这就是我复制它的方式。可以说我确实有两个模型类型的对象,它们具有上面声明和实现的扩展方法。
let modelA = Model()
let modelB = Model()
let attributedStringA = modelA.attributedString()
let attributedStringB = modelB.attributedString()
我已经在上面记录了两个属性字符串,我希望它分别显示
modelA
和modelB
属性,但是相反,它在两个属性字符串上只产生modelA
要添加有关该问题的更多数据。上面生成的图标是自定义字体FontAwesome,它也会产生一个属性字符串,并放在
Model
属性字符串的前面(使用系统字体)。我已经在产生所需属性的报表上运行了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()
添加垃圾属性后,它现在可以完美运行;因为此扩展方法以前没有再为属性字符串的Icon部分保留更多的挥之不去的属性
关于ios - 先前的属性在后续调用中传播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48255821/