Search code examples
objective-ccocoadynamicpluginscocoa-design-patterns

Dynamically load custom plugins (libraries) in a Cocoa application


I have developed a Cocoa application for Mac OS X. I want to make some custom plugins (with interface too) and dynamically load them in my app. My app should look inside a folder and retrieve all files (the plugins) and make them available in the user interface.

Can someone suggest me a starting point?

How can I load them dynamically, the plugins must be dynamic libraries or sth?

Thanks.


Solution

  • You want to take a look at NSBundle. A loadable bundle (a Framework is a loadable bundle) project will produce what you want. If you set the principleClass property of the bundle to the top-level class of your plugin, then you can retrieve an instance of the class from the loaded bundle. You can load a bundle at a given path with

    id bundle = [NSBundle bundleWithPath:pathToBundle];
    NSError *err;
    if(![bundle loadAndReturnError:&err]) {
      // err contains error info
    } else {
      // bundle loaded properly
      Class pluginClass = [bundle principleClass];
      // instantiate pluginClass and off you go...
    }