Objective-C, using protocol to access datasource
I'm using the MVC model but I cannot get the data needed for the View, I am trying to use a data source since a View should never own its data. Typically, a protocol is used to create a data source.
- I have a MVC: CalculatorBrain.[hm] - CalculatorViewController.[hm] - (view is .xib)
- I also have MVC: GraphingView - GraphingViewController - (model is the data I can't get)
The goal is: when I press a button on the calculator, it draws the function (e.g.: x+5=) that is currently in it's dis开发者_运维技巧play. The calculator part takes care of the expression/function, the display, etc while the graphing part should draw. CalculatorViewController should be the GraphingView's source, but the data always stays null.
This is GraphingView.h with the declaration of the protocol :
@class GraphingView;
@protocol GraphingViewSource
- (float)getDataPoints:(GraphingView *)requestor;
@end
@interface GraphingView : UIView {
id <GraphingViewSource> source;
}
@property (assign) id <GraphingViewSource> source;
@end
CalculatorViewController.m implements the protocol by implementing the getDataPoints: method. Header of CalculationViewController.h :
@interface CalculatorViewController : UIViewController <GraphingViewSource>
Pressing the button which should set up the data source :
- (IBAction)graphPressed:(UIButton *)sender
{
GraphingViewController *graphingVC = [[GraphingViewController alloc] init];
graphingVC.graphingView.source = self;
[self.navigationController pushViewController:graphingVC animated:YES];
[graphingVC release];
}
Pressing the button brings up the new view nicely etc, but following line of code only returns null (inside GraphingView.m) :
float result = [self.source getDataPoints:self];
It seems, I cannot access my data source...
From your comments it seems that graphingView
is nil
at the time you are trying to set its source.
If there is a xib for the view controller, you should be doing this:
GraphingViewController *graphingVC = [[GraphingViewController alloc] initWithNibName:@"GraphingViewController" bundle:nil];
Instead of a plain init
.
This will create and instantiate all of your view objects so they are available to have properties set before you present the view controller.
精彩评论