【问题标题】:CFDictionaryGetValue throws EXC_BAD_ACCESSCFDictionaryGetValue 抛出 EXC_BAD_ACCESS
【发布时间】:2019-12-23 17:08:56
【问题描述】:

我在 Objective-C 中发现了一个从 Getting graphic card information in objective C 截取的代码,我目前正在尝试将其转换为 Swift。 我正在尝试从CFMutableDictionary 中读取一个值(代码如下)。但是,当我调用函数CFDictionaryGetValue 时,我得到一个错误: “线程 1:EXC_BAD_ACCESS(代码=1,地址=0x656d614e4f60)”

这是我当前的代码:

static func getGpuName() {
        var iterator: io_iterator_t = 0
        let errCode: kern_return_t  = IOServiceGetMatchingServices(kIOMasterPortDefault, IOServiceMatching("IOPCIDevice"), &iterator)
        if errCode != kIOReturnSuccess {
            fatalError("Could not retrieve the service dictionary of \"IOPCIDevice\"")
        }

        // iterate over the pci devices
        var device = IOIteratorNext(iterator)
        while device != 0 {
            var unmanagedServiceDictionary: Unmanaged<CFMutableDictionary>?
            if IORegistryEntryCreateCFProperties(device, &unmanagedServiceDictionary, kCFAllocatorDefault, 0) != kIOReturnSuccess {
                IOObjectRelease(device)
                continue
            }

            if let serviceDictionary: CFMutableDictionary = unmanagedServiceDictionary?.takeRetainedValue() {
                let name = CFDictionaryGetValue(serviceDictionary, "IOName")
            }

            // release the device
            IOObjectRelease(device)

            // get the next device from the iterator
            device = IOIteratorNext(iterator)
        }
}

有人知道我如何读取CFMutableDictionary 的值吗?

谢谢:)

【问题讨论】:

    标签: objective-c swift macos core-foundation


    【解决方案1】:

    处理 CoreFoundation API 真的很痛苦。

    发生错误是因为您不能将文字 String 作为 CFDictionaryGetValue 的第二个参数传递,该参数必须是 UnsafeRawPointer

    但是,解决方案非常简单。将字典转换为 Swift 字典

    if let serviceDictionary = unmanagedServiceDictionary?.takeRetainedValue() as? [String:Any] {
        if let name = serviceDictionary["IOName"] as? String {
            print(name)
        }
    } 
    

    【讨论】:

      【解决方案2】:

      好的,经过更多研究,我仍然不知道为什么会抛出错误。但是,我通过将字典转换为 NSDictionary 找到了解决方法。

      以下代码现在可以使用:

      let serviceDictionary: NSDictionary = (unmanagedServiceDictionary?.takeRetainedValue())! as NSDictionary
      if let name = serviceDictionary.value(forKey: "IOName") as? String {
          print(name)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多