Can you do some form of dependency injection in objective-c?

I am currently hard-coding another object directly when necessary, and I need the ability to use this through the init method (suppose?). In the code below, I create a new HatService in the viewDidLoad method, and I would prefer not to do this for validation / communication reasons.

- (void)viewDidLoad
{
    [super viewDidLoad];
    HatService* hatService = [[HatService alloc] init];
    [hatService getHatById:self];
}

The first question is how to do this in objective-c? Second question. Should I worry about it or do it at all?

Update

Here's what I'm starting, but I never came across the first init method at runtime. I both declared in the interface - anything else that I missed that would allow me to override this init method and inject the service dependency?

. , , appDeleage , , ( , init?)

-(id)initWithHatService:(HatService *)service
{
  if (self = [super init])
  {
    [self setService:service];
  }
  return self;
}

-(id)init
{
  HatService* hatService = [[HatService alloc] init];
  return [self initWithHatService:hatService];
}
+3
3

UIViewController - (id)initWithNibName:(NSString *)nibName bundle:(NSBundle *)nibBundle. , , nib, , . , , -.

-, -init, :

- (id)init {
    return [self initWithHatService:nil];
}

init .

, , init. , .

MyViewController *newContrlr = [[MyViewController alloc] initWithNibName:nil bundle:nil];
newContrlr.hatService = [[[HatService alloc] init] autorelease];
+6

, init , init . .. - (id) initWithHatService:(HatService *)serv; init , objective-c.

: -getHatById: . ? get-prefixed Cocoa.

+1

Objective-C. , " ", .

. DI Typhoon: http://www.typhoonframework.org

0
source

Source: https://habr.com/ru/post/1784373/


All Articles