In the process of attempting to convert my previously singleton-based-global-controller classes to more OOP friendly dependency injection method of passing the required methods from one object to another as they are needed. I’ve run into the problem where my previous class used a global object during its init.
(id)init
{
self = [super init];
if (self)
{
[self setUpPhysicsWithWorld:FMPresenter.physics.world];
}
return self;
}
Where FMPresenter.physics returned a singleton physics object. Since my object cannot be instantiated correctly without a Physics object, a call to init is not valid. I have seen this being used:
(id) init
{
NSAssert(NO, @"init not allowed");
[self release];
return nil;
}
(id) initWithPhysics:(FMPhysics*)physics
{
self = [super init];
if (self) {
[self setUpPhysicsWithWorld:physics.world];
}
return self;
}
Is this the preferred method to enforce constructor parameters in Objective-C?
Yes your solution is correct, the preferred way is to create another method that starts with init and to which you pass the required initialization parameters and return self, after a call to super.