Instantiate Object from AnyClass

I'm pulling my bundle url and class name from a string, and I'd like to instantiate an object.


The code looks like this:


var cocoaViewBundleURL = cocoaViewInfo.mCocoaAUViewBundleLocation.takeRetainedValue();
var factoryClassName = cocoaViewInfo.mCocoaAUViewClass?.takeRetainedValue();
       
var bundle = NSBundle(URL: cocoaViewBundleURL);
var factoryClass = bundle?.classNamed(factoryClassName!);
var factory = factoryClass();


It doesn't compile.


What is the proper way to do this with swift?

Accepted Answer

Two things you need to instantiate meta-type object:

- The type needs to be exlicitly declared as having initializer

- You need to use `init` notation

The return type of classNamed(_:) is AnyClass, which is just an alias of AnyObject.Type, and AnyObject is not declared as having initializer.


Try modifying two lines as follows:

    let factoryClass = bundle?.classNamed(factoryClassName!) as! NSObject.Type
    let factory = factoryClass.init()

Thanks!


This works with the following code:


var bundle = NSBundle(URL: cocoaViewBundleURL);
var factoryClass = bundle?.classNamed(factoryClassName!) as NSObject.Type;
var factory :Void = factoryClass.initialize();

I just wanted to update that this is the actual code that's working, not the previous:


var bundle = NSBundle(URL: cocoaViewBundleURL);
var factoryClass = bundle?.classNamed(factoryClassName!) as NSObject.Type?;
var factory :NSObject? = factoryClass?();
Instantiate Object from AnyClass
 
 
Q