循环遍历 CFURL 的 CFArray

Looping through a CFArray of CFURL

使用 Swift,我试图循环遍历 CFURL 的 CFArray,但出现 EXC_BAD_INSTRUCTION 错误。

let apps = LSCopyApplicationURLsForURL(NSURL(string: "http://www.yahoo.com")! as CFURL, LSRolesMask.all)!

let finalArray = apps.takeRetainedValue()

let count = CFArrayGetCount(finalArray)

for ix in 0...count-1 {
    let url = CFArrayGetValueAtIndex(finalArray, ix) as! CFURL
    print(url)
}

我做错了什么?

你真的想一直呆在CoreFoundation的深渊里吗?将数组转换为 [URL]

if let apps = LSCopyApplicationURLsForURL(URL(string: "http://www.yahoo.com")! as CFURL, LSRolesMask.all)?.takeRetainedValue() {
    for url in apps as! [URL] {
        print(url)
    }
}

顺便说一下,错误的发生是因为 CFArrayGetValueAtIndex returns 一个指针无法转换为 CFURL

你必须这样写

for ix in 0..<count {
    let url = unsafeBitCast(CFArrayGetValueAtIndex(finalArray, ix), to: URL.self)
    print(url)
}

您只需要做:

let urls = cfArr as? Array<URL>

示例:

if let retainedArr = LSCopyApplicationURLsForURL(URL(fileURLWithPath: "/Users/uks/Desktop/taopixie4.png") as CFURL, .all)?.takeRetainedValue(),

let listOfRelatedApps = retainedArr as? Array<URL>