尝试从macOS中的粘贴板获取文本时出现错误
问题描述:
我想从剪贴板中获取文本。我编写了一个似乎可以正常工作的代码,但有时会崩溃,例如,当我以guest用户身份登录时,尝试使用该应用程序时。也许是因为Pasterboard不能包含文字。尝试从macOS中的粘贴板获取文本时出现错误
这是我正在使用的代码,我想将最后一行包含在条件语句中,但似乎太晚了,因为那时我收到一个错误。
func pasteOverAction() {
// create a pasteboard instance
let pasteboard = NSPasteboard.general()
// create an array for put pasteboard content
var clipboardItems: [String] = []
// iterate elements in pasteboard
for element in pasteboard.pasteboardItems! {
// if it's text
if let str = element.string(forType: "public.utf8-plain-text") {
clipboardItems.append(str) // put in the array
}
}
// put the first element of the array in a constant
// sometimes crashes here
let firstStringOfClipboard = clipboardItems[0]
}
答
我发现了这个问题。当在剪贴板中还没有文本时(例如,当您刚刚使用访客用户登录时),创建的数组中没有项目,并且出现超出范围的错误。我通过添加一个检查来解决这个错误。
除了虚线之间的部分外,代码与问题的代码类似。
func pasteOverAction() {
// create a pasteboard instance
let pasteboard = NSPasteboard.general()
// create an array for put pasteboard content
var clipboardItems: [String] = []
// iterate elements in pasteboard
for element in pasteboard.pasteboardItems! {
// if it's text
if let str = element.string(forType: "public.utf8-plain-text") {
clipboardItems.append(str) // put in the array
}
}
// Added part ----------------------------------------
// avoid out of range if there is not a tex item
let n = clipboardItems.count
if n < 1 {
NSBeep() // warn user that there is not text in clipboard
return // exit from the method
}
// ---------------------------------------------------
// put the first element of the array in a constant
// now don't crashes here anymore
let firstStringOfClipboard = clipboardItems[0]
}
你的问题是'.pasteboardItems!'。你不应该强制解开一个可选的。相反,处理这个属性为零的可能性。 – Moritz
UTI类型应该是“public.plain-text” –