Objective-C构造函数中的必需参数

Ara*_*yan 3 constructor objective-c

在尝试将我之前基于单件的全局控制器类转换为更多OOP友好依赖注入方法的过程中,该方法在需要时将所需方法从一个对象传递到另一个对象.我遇到了我的上一课在init期间使用全局对象的问题.

(id)init 
{
    self = [super init];
    if (self) 
    {
        [self setUpPhysicsWithWorld:FMPresenter.physics.world];
    }
    return self;
}
Run Code Online (Sandbox Code Playgroud)

FMPresenter.physics返回一个单独的物理对象.由于我的对象在没有Physics对象的情况下无法正确实例化,因此调用init无效.我看到过这个用过:

(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;
}
Run Code Online (Sandbox Code Playgroud)

这是在Objective-C中强制构造函数参数的首选方法吗?

Osc*_*mez 5

是的,你的解决方案是正确的,首选的方法是创建另一个以init开头的方法,并在调用super之后传递所需的初始化参数并返回self.