遍历CFURL的CFArray

时间:2019-06-24 22:13:21

标签: swift core-services

使用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)
}

我在做什么错了?

1 个答案:

答案 0 :(得分:2)

您真的想留在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返回了不能转换为CFURL的指针

您将不得不写类似

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