NSObject cast to it's actual content

Getting there. New issue while scanning QR codes. When a code is detected I need to convert an NSObject to what it actually is, an AVMetadataMachineReadableCodeObject. In the debugger I can see this as the description.

How can I convert/cast/extract the AVMetadataMachineReadableCodeObject or it’s superclass AVMetadataObject from the metadataObject ?

Many thanks in advance.
(BTW Multi-OS Engine works great!)

public class ScanController extends UIViewController implements AVCaptureMetadataOutputObjectsDelegate
{
    @Override
    public void captureOutputDidOutputMetadataObjectsFromConnection( AVCaptureOutput captureOutput, NSArray<?> metadataObjects, AVCaptureConnection connection )
    {
        for( Object metadataObject : metadataObjects )
        {
            try
            {
                boolean isInstance = metadataObject instanceof AVMetadataMachineReadableCodeObject; // always false
                AVMetadataObject data = ( AVMetadataObject ) metadataObject; // << FAILS
                if( data.type().equals( AVFoundation.AVMetadataObjectTypeQRCode() ) )
                {
                    AVMetadataMachineReadableCodeObject qrCode;
                    qrCode = ( AVMetadataMachineReadableCodeObject ) previewLayer.transformedMetadataObjectForMetadataObject( data );
                    foundQRCode( qrCode.stringValue() );
                }
            }
            catch( Exception e )
            {
                e.printStackTrace();
            }
        }
    }
}

Dear gradle42,

please try to add this to your class:

static {
    Class.forName(AVMetadataMachineReadableCodeObject.class.getName());
}

In some cases this trick is required to ensure class initialization required by NatJ (MOE’s bridge to the Objective-C and C world). In most cases where you get a class cast exception and the cast should be valid, try this trick.

1 Like

Fantastic! This worked. Thank you so much.

I had this same issue with CLLocationManager.locationManagerDidUpdateLocations(CLLocationManager manager, NSArray<? extends CLLocation> locations)

It would complain at runtime that it cannot convert an NSObject to a CLLocation. Adding the static conversion fixed the error.

Update, had the same issue with a CLRegion update as well. This seems to be a serious issue.

I encountered this problem today in CLGeocoder reverseGeocodeLocationCompletionHandler(NSArray<? extends CLPlacemark> arg0, NSError arg1) with a ClassCastException on CLPlacemark.

The workaround fixed the problem, thank you!