是什么导致 UIPasteboard 中的项目被转换为 NSConcreteMutableData?

What is causing items from UIPasteboard to be converted to NSConcreteMutableData?

我是 运行 操场上的以下人员(我在 Xcode 7.3.1 和 Xcode 8.1 中进行了测试,看到了相同的行为):

import UIKit

let key: String = "some_key"
let value: String = "some_value"

UIPasteboard.general.items = [[key: value]]

let item = UIPasteboard.general.items.first
if let item = UIPasteboard.general.items.first {
    switch item[key] {
    case let x as String:
        print("This is expected")
    case let x as Any:
        type(of: x)
        print("This is unexpected")
    default:
        print("This is unexpected")
    }
} else {
    print("This is unexpected")
}

而且我注意到我放入粘贴板的 String 实际上被桥接为 NSConcreteMutableData

我的问题如下:

  1. 这是由内部 UIPasteboard 实现引起的(即从 NSString 显式转换为 NSConcreteMutableData),还是这个标准的 ObjC-Swift 桥接行为?

  2. 如何解决此问题以在 UIPasteboard 中存储自定义 key/value 对?

为了便于参考,这是在操场上的样子:

您为 item[key] 获得的 Data 只是字符串的 UTF-8 编码值。

如果添加以下内容 case,您将看到:

case let x as Data:
    let str = String(data: x, encoding: .utf8)
    print("str = \(str)")

造成混淆的原因是 items 属性 使用的密钥是 UTI,而不是随机密钥。如果您将密钥更改为 public.text,那么您的代码将按预期工作。

通常,您不会使用 items 属性 将字符串放在粘贴板上。您将使用 string 属性 来读取和写入值。

UIPasteboard.general.string = "Hello"
let aStr = UIPasteboard.general.string
print("aStr = \(aStr)")

这样做可以避免指定 UTI 的需要,也可以避免替换粘贴板上的所有现有项目。