プロトコル プロパティ インスタンスの具象クラスを注入するために、依存性注入に Objection を利用しようとして少し混乱しています。学習目的で、次のように簡単なロガー インジェクションの例を作成しました。
// Protocol definition
@protocol TestLogger<NSObject>
-(void)trace: (NSString*) message, ...;
-(void)info: (NSString*) message,...;
-(void)warn: (NSString*) message,...;
-(void)error: (NSString*) message, ...;
@end
// Concrete class definition following my protocol - note it doesn't actually use
// CocoaLumberjack yet, I just had an NSLog statement for testing purposes
@interface CocoaLumberjackLogger : NSObject<TestLogger>
@end
// Implementation section for lumberjack logger
@implementation CocoaLumberjackLogger
-(void)trace: (NSString*) message, ...
{
va_list args;
va_start(args, message);
[self writeMessage:@"Trace" message:message];
va_end(args);
}
//(note: other implementations omitted here, but are in my code)
.
.
.
@end
ここで、ロガーをプロパティとしてビューに挿入したいので、次のようにします。
// My test view controller interface section
@interface TestViewController : UIViewController
- (IBAction)testIt:(id)sender;
@property id<TestLogger> logger;
@end
// Implementation section
@implementation TestViewController
objection_register(TestViewController)
objection_requires(@"logger")
@synthesize logger;
.
.
.
最後に、アプリケーション モジュールのセットアップを行います。
@interface ApplicationModule : JSObjectionModule {
}
@end
@implementation ApplicationModule
- (void)configure {
[self bindClass:[CocoaLumberjackLogger class] toProtocol:@protocol(TestLogger)];
}
@end
@implementation TestAppDelegate
@synthesize window = _window;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions: (NSDictionary *)launchOptions
{
JSObjectionModule *module = [[ApplicationModule alloc] init];
JSObjectionInjector *injector = [JSObjection createInjector:module];
[JSObjection setDefaultInjector:injector];
return YES;
}
結果
テスト ボタンをクリックしてロガー ステートメントを呼び出すと、テスト ビューでロガー プロパティだけが nil になります。具体的なクラス タイプ CococoaLumberJackLogger のオブジェクトで埋められることを望んでいました。
私がどこで間違ったのかについてのアイデアはありますか? どんな助けでも大歓迎です。ありがとう!