面试题答案
一键面试依赖注入在Objective-C模块化设计中的实现方式
- 属性注入(Property Injection):通过对象的属性来传递依赖对象。在类的定义中,声明一个属性用于存储依赖对象,然后在需要使用依赖对象的地方,通过设置该属性的值来注入依赖。
- 构造函数注入(Constructor Injection):在类的初始化方法(通常是
init
系列方法)中,将依赖对象作为参数传入,在初始化过程中保存依赖对象,以便后续使用。 - 方法注入(Method Injection):定义一个方法,该方法接受依赖对象作为参数,在需要使用依赖对象的逻辑中调用这个方法并传入依赖对象。
举例:属性注入在简单场景中的应用
假设我们有一个ViewController
类,它需要依赖一个NetworkService
类来进行网络请求。
首先定义NetworkService
类:
@interface NetworkService : NSObject
- (void)fetchData;
@end
@implementation NetworkService
- (void)fetchData {
NSLog(@"Fetching data from network...");
}
@end
然后定义ViewController
类,使用属性注入NetworkService
:
@interface ViewController : UIViewController
@property (nonatomic, strong) NetworkService *networkService;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
if (self.networkService) {
[self.networkService fetchData];
}
}
@end
在使用ViewController
的地方,进行依赖注入:
NetworkService *service = [[NetworkService alloc] init];
ViewController *vc = [[ViewController alloc] init];
vc.networkService = service;
这样,ViewController
就通过属性注入的方式获得了NetworkService
的实例,从而可以使用其功能进行网络请求相关操作。