尝试使用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;
}
结果
当我点击我的测试按钮调用记录器语句时,一切似乎都运行得很好,我的测试视图中只有我的logger属性为nil。我希望它能填充一个具体类类型CococoaLumberJackLogger的对象。
关于我哪里出错的任何想法?任何帮助是极大的赞赏。谢谢!
答案 0 :(得分:2)
肖恩,
负责初始化TestViewController的是什么?必须将TestViewController的初始化委托给进样器。
例如,如果NIB负责实例化它,则记录器将为零,因为NIB不了解TestViewController的依赖性。