0

プロトコル プロパティ インスタンスの具象クラスを注入するために、依存性注入に 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 のオブジェクトで埋められることを望んでいました。

私がどこで間違ったのかについてのアイデアはありますか? どんな助けでも大歓迎です。ありがとう!

4

1 に答える 1

2

ショーン

TestViewController の初期化を担当するのは何ですか? TestViewController の初期化は、インジェクターに委譲する必要があります。

たとえば、NIB がそれをインスタンス化する責任がある場合、NIB は TestViewController の依存関係を理解し​​ていないため、ロガーは nil になります。

于 2012-07-19T01:35:19.197 に答える