Search code examples
macosswiftswift2iokit

Swift2: Correct way to initialise UnsafeMutablePointer<Unmanaged<CFMutableDictionary>?> parameter to pass to IORegistryEntryCreateCFProperties


Ok, so in Swift 2, the definition for IORegistryEntryCreateCFProperties is

func IORegistryEntryCreateCFProperties(entry: io_registry_entry_t, _ properties: UnsafeMutablePointer<Unmanaged<CFMutableDictionary>?>, _ allocator: CFAllocator!, _ options: IOOptionBits) -> kern_return_t

I can do

var dict: UnsafeMutablePointer<Unmanaged<CFMutableDictionary>?> = nil
kr = IORegistryEntryCreateCFProperties(box as io_registry_entry_t, dict, kCFAllocatorDefault, nilOptions)

which compiles and runs. Of course it crashes when it executes the IORegistryEntryCreateCFProperties because dict is initialised to nil. My question is how to initialise dict to a non-nil value? I've tried various approaches without success.


Solution

  • A parameter of the type

    UnsafeMutablePointer<Unmanaged<CFMutableDictionary>?>
    

    means that you have to pass a variable of the type

    Unmanaged<CFMutableDictionary>?
    

    as an inout-argument with &. On success, you can unwrap the optional (with optional binding), convert the unmanaged object to a managed object with takeRetainedValue(), and finally (if you want), cast the CFMutableDictionary to NSDictionary.

    Example:

    var props : Unmanaged<CFMutableDictionary>?
    if IORegistryEntryCreateCFProperties(entry, &props, kCFAllocatorDefault, 0) == KERN_SUCCESS {
        if let props = props {
            let dict = props.takeRetainedValue() as NSDictionary
            print(dict)
        }
    }