1

I am quite new to Objective-C but have quite a bit of experience in C#. I am trying to check out some dependency injection frameworks in Objective-C. While looking into some frameworks, i found something very different with respect to the constructors/Initializers in an Objective-C class.

If i want to inject an object through a constructor like below,

-(id)initWithService:(id<ServiceProtocol>)service;

of course this won't be the default constructor and the control will not enter here until this is called from some other place.

only -(id)init is the default constructor and the control goes here when this object is injected.

So i am wondering if its a good practice to call initWithService from -(id)init ?

Or for every class just have two initializers use the initializer with constructor only during mocking and ignore it during the auto initialization process by the framework ?

golldy
  • 1,279
  • 1
  • 15
  • 31
  • I don't really follow your scenario exactly, but I'll state my opinion that if you're doing something different just to satisfy some mocking tool, you're doing it wrong. – Avi Mar 28 '16 at 06:20
  • To be honest, i do not want to use any tool as such. This is plain objective-C question. What would you do if you can't custom init but u can only init. – golldy Mar 28 '16 at 06:39
  • Sounds like you want to make `initWithService:` [your designated initialiser](http://stackoverflow.com/a/26186421/2976878), and maybe even [make `init` unavailable](https://craftbeercraftcode.com/2014/12/28/better-brewing-with-ns_unavailable/) if you have no default value for it. – Hamish Mar 28 '16 at 07:30

1 Answers1

-2


As written here https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/ProgrammingWithObjectiveC/Introduction/Introduction.html#//apple_ref/doc/uid/TP40011210-CH1-SW1
The best practice is to use designated initialiser in such way

-(instanceType)initWithYourNeeds:(SomeClassName *)obj
{
    if(self==[super init])
    {
        //do some stuff here
    }
   retur self;
}
Karaban
  • 151
  • 8
  • I am not sure you understood my question right. What would you do if you cannot init with objects? – golldy Mar 28 '16 at 06:39
  • 1
    You set a property after performing the initialization. This is common when loading views from xibs, as you don't have control over which initializer is called by the xib-loading mechanism. – Avi Mar 28 '16 at 07:21