【问题标题】:Assign Data Model to View Controller in appDelegate with Storyboards - ios使用 Storyboards 将数据模型分配给 appDelegate 中的视图控制器 - ios
【发布时间】:2013-12-20 23:43:40
【问题描述】:

没有Storyboards,我曾经在AppDelegatedidFinishLaunchingWithOptions中使用此代码将Data Model分配给View Controller

//Data Model Class
DataModel *model=[[DataModel alloc] init];

// TableViewController
Controller *controller=[[Controller alloc] initWithModel:model style:UITableViewStylePlain];

self.window.rootViewController=controller;

view ControllerinitWithModel方法中:

-(id)initWithModel:(SBQAllReadersModel *) aModel
             style:(UITableViewStyle)    aStyle{

    if (self=[super initWithStyle:aStyle])
    {
        _model=aModel;
    }

    return self;
}

但是Storyboards 我做不到:

//Data Model Class
DataModel *model=[[DataModel alloc] init];

UIStoryboard *mainStoryboard = [UIStoryboardstoryboardWithName:@"MainStoryboard" bundle: nil];

Controller *controller = [mainStoryboard instantiateViewControllerWithIdentifier:@"Controller"];

controller.model=model;

问题是在Storyboards 中我不能使用View Controllerinit 方法,因为Storyboard 无法识别它。我必须使用它不能被覆盖的initWithCoder:,并且我不能将参数传递给awakeFromNib

您建议我将data modelStoryboardsappDelegate 分配给Controllers

非常感谢

【问题讨论】:

    标签: ios storyboard uistoryboard appdelegate


    【解决方案1】:

    鉴于 DataModel 的分配方式,我认为第一个视图控制器中的惰性 getter 是优越的(甚至比你以前的做法)。例如

    // in Controller.m private interface declare @property(strong,nonatomic) DataModel *dataModel, then...
    
    - (DataModel *)dataModel {
        if (!_dataModel) {
            _dataModel = [[DataModel alloc] init];
        }
        return _dataModel;
    }
    

    【讨论】:

    • 谢谢!!请看我的回答。
    【解决方案2】:

    view controllerinitWithCoder: 中我分配了模型。

    -(id)initWithCoder:(NSCoder *)aDecoder{
        if(self = [super initWithCoder:aDecoder])
        {
            // Do something
            _model=[[DataModel alloc] init];
        }
        return self;
    }
    

    是的,最好使用你说的惰性吸气剂;)

    那么我是否必须在rootViewControler 中分配model 并通过delegation 将模型传递给需要使用它的下一个控制器?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-08-04
      • 2015-02-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多