0

So the question is like this:

I subclass 2 classes, which is UIView(name: Menu) and UIViewController(name: MainController). In Menu, i used xib file to create it layout. In MainController, i added Menu as subview like this and comform to protocol in Menu.

SliderMenu *sliderMenu = [[[NSBundle mainBundle] loadNibNamed:@"SliderMenu" owner:self options:nil] objectAtIndex:0];
sliderMenu.datasource = self;
sliderMenu.delegate = self;
[self.view addSubview:sliderMenu];

The layout works perfectly, there is no problem with it.

The problem is with DataSource. i call a datasource method in awakeFromNib

- (void)awakeFromNib {
// Alloc data
self.data = [[NSArray alloc] initWithArray:[self.datasource arrayOfData]];
}

and that never even get called. After trying and trying i found out that, sliderMenu.datasource = self;is run after awakeFromNib. Thats is why the datasource method in MainController is never get called.

Question: How can i solve this problem?

4

1 回答 1

0

如果在-awakeFromNib方法中设置断点,您将看到该方法按应有的方式执行。问题是,这个方法在数据源分配之前调用,而此时你的self.datasourceis nil
我建议您覆盖datasource属性的设置器并在那里初始化您的数据,例如

- (void)setDatasource:(id<YourProtocol>)datasource
{
    _datasource = datasource;
    self.data = [[NSArray alloc] initWithArray:[datasource arrayOfData]];
}

或者

例如,创建一个公共方法,prepare并在那里进行所有初始化,

- (void)prepare
{
    self.data = [[NSArray alloc] initWithArray:[self.datasource arrayOfData]];
}

并在数据源分配后调用此方法:

SliderMenu *sliderMenu = [[[NSBundle mainBundle] loadNibNamed:@"SliderMenu" owner:self options:nil] objectAtIndex:0];
sliderMenu.datasource = self;
sliderMenu.delegate = self;
[sliderMenu prepare];
[self.view addSubview:sliderMenu];
于 2015-04-26T12:33:42.863 回答