简体   繁体   中英

from Objective-C to Swift 4 perform selector

I am new to both Swing and Objective-C and I was trying to work with AVCaptureDevice.

I tried to implement the following code that gives me back a private member of an AVCaptureDevice instance in Objective-C. But I am no able to transfer the same instruction to Swift:

CMIOObjectID connectionID;
AVCaptureDevice *main_cam = (AVCaptureDevice*)[cameras objectAtIndex:0];
connectionID = [main_cam performSelector:NSSelectorFromString(@"connectionID") withObject:nil];

Mainly because the

main_cam.perform(NSSelectorFromString("connectionID"), with: nil) 

in Swift returns an

Unmanaged<AnyObject>  

and does not accept a forced cast to CMIOObjectID.

Is it possible to perform the operation in Swift?

Using @convention(c)

let selector = NSSelectorFromString("connectionID")
let methodIMP: IMP! = main_cam.method(for: selector)
let result: CMIOObjectID? = unsafeBitCast(methodIMP,to:(@convention(c)(AVCaptureDevice?,Selector)-> CMIOObjectID?).self)(main_cam,selector) 

More details of this approach in my answer here

You can try:

let unmanaged = main_cam.perform(Selector(("connectionID")), with: nil)
if let connectionID = unmanaged?.takeUnretainedValue() as? CMIOObjectID {
    // do your thing
}

You can read about how to use Unmanaged here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM