Cocoa でのプラグインは、バンドルを動的に読み込むことで実現できる。 特定の名前のクラスをバンドルに用意しておいて、バンドルを読み込んだあとにそのクラスのインスタンスを作るだけだ。
バンドルの作り方。
メニューの「新規プロジェクト」から「Cocoa Bundle」を作成。
「ターゲット」タブの詳細設定ビューで「WRAPPER_EXTENSION」を「plugin」などとすることで任意の拡張子のバンドルが用意できる。
読み込み方。
まずはプラグインのパスを検索する。以降の説明では、プラグインは拡張子「.plugin」を持ち、実行ファイル(つまりメインのバンドル)と同じ位置にある「Plug-Ins」フォルダに置かれるものとする。
NSString *bundlePath = [NSBundle mainBundle bundlePath];
NSString *basePath = [bundlePath stringByDeletingLastPathComponent];
NSString *pluginPath = [basePath stringByAppendingPathComponent:@"Plug-ins"];
NSArray *pluginList = [NSBundle pathsForResourcesOfType:@"plugin" inDirectory:pluginPath];
次に、それぞれのプラグインのバンドルを読み込んでインスタンスを作成する。特定のプロトコルを実装させて、それの実装を確認するのが確実なやり方であろう。
NSBundle *pluginBundle = NSBundle bundleWithPath:path;
if (pluginBundle) {
Class pluginClass = pluginBundle classNamed:@"MyPlugin";
if (pluginClass conformsToProtocol:@protocol(MyPluginProtocol)) {
MyPlugin plugin = [pluginClass alloc init];
}
}
プラグインのプロトコルとしては、プラグイン名、バージョン、作者名の取得メソッドを用意するのが有用である。
詳しくは参考資料を参照のこと。
コメントを書く