此代码是否显示CFAttributedString不是线程安全的?或者我在设置中做错了什么?CFAttributedString线程安全
我认为CFAttributedString可以安全地从多个线程读取,但是我看到每隔几次运行就会在这段代码中崩溃。
@IBAction func testIt(_ sender: Any?) {
let testString = "Hello world! Lets make this a bit longerrrrrrrrrrrrrrrr." as CFString
let testStringLength = CFStringGetLength(testString)
let testAttributedString = CFAttributedStringCreateMutable(kCFAllocatorDefault, testStringLength)
CFAttributedStringReplaceString(testAttributedString, CFRange(location: 0, length: 0), testString)
CFAttributedStringEndEditing(testAttributedString)
for i in 0..<testStringLength {
let range = CFRange(location: i, length: 1)
let keyAndValue = "\(i)" as CFString
CFAttributedStringSetAttribute(testAttributedString, range, keyAndValue, keyAndValue)
}
let immutableTestAttributedString = CFAttributedStringCreateCopy(kCFAllocatorDefault, testAttributedString)
DispatchQueue.concurrentPerform(iterations: 100) { _ in
var index: CFIndex = 0
var effectiveRange: CFRange = CFRange(location: 0, length: 0)
while index < testStringLength {
// Crash happens here EXC_BAD_ACCESS (code=1, address=0x24)
let _ = CFAttributedStringGetAttributes(immutableTestAttributedString, index, &effectiveRange)
index = effectiveRange.location + effectiveRange.length
}
}
}
感谢您的提示,不幸的是,当我以这种方式创建字符串时,我仍然在同一个地方看到一个错误。在这种情况下使用CFAttributedString的原因是因为它在代码中是一个热门的地方,CFAttributedStringSetAttribute看起来运行速度快很多,然后用NSMutableAttributedString添加属性。 –
您是否有任何关于如何快速桥接工作的更多信息?尤其要注意性能问题。我在Swift的Core Text上做了很多工作,现在处于优化阶段。谢谢。 –
谢谢,你的帮助。我期待线程安全,因为NSAttributedString被列为安全,并且Core Foundation被广告为“通常”安全:https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/ThreadSafetySummary/ThreadSafetySummary.html但在这种情况下,非常了解并再次感谢您的帮助。 –