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;
}

结果

一切似乎都运行得很好,当我单击测试按钮调用记录器语句时,只有我的记录器属性在我的测试视图中为零。我希望它会被一个具体类类型 CococoaLumberJackLogger 的对象填充。

关于我哪里出错的任何想法?任何帮助是极大的赞赏。谢谢!

4

1 回答 1

2

肖恩,

什么负责初始化 TestViewController?TestViewController 的初始化必须委托给注入器。

例如,如果一个 NIB 负责实例化它,那么记录器将为 nil,因为 NIB 不了解 TestViewController 的依赖关系。

于 2012-07-19T01:35:19.197 回答