I've been wrestling with this for a few days - I have a custom protocol that is supposed to get the data from one of my models (via it's controller) to a view that graphs it.
Here's how I am doing this - step by step:
In graphing view, I declare the protocol as follows:
@class GraphView;
@protocol GraphViewDataSource <NSObject>
-(CGFloat)yValueForGraphView:(GraphView *)sender usingXval:(CGFloat)xVal;
@end
I then declare a property in view.h
@interface GraphView : UIView
@property (nonatomic, weak) IBOutlet id <GraphViewDataSource> dataSource;
@end
I synthesize the property in view.m:
@synthesize dataSource=_dataSource;
Then in my drawRect, I am calling this method to bring me back a CGFloat from another controller's model:
-(void) drawRect:(CGRect)rect
{
//context stuff, setting line width, etc
CGPoint startPoint=CGPointMake(5.0, 6.0);
NSLog(@"first, y value is: %f", startPoint.y);
startPoint.y=[self.dataSource yValueForGraphView:self usingXval:startPoint.x]; //accessing delegate via property
NSLog(@"now the y value now is: %f", startPoint.y);
//other code..
}
Now in my other view controller, I am importing the view.h file and declaring that it conforms to the protocol:
#import "GraphView.h"
@interface CalculatorViewController () <GraphViewDataSource>
Creating a property for the GraphView:
@property (nonatomic, strong) GraphView *theGraphView;
Synthesize:
@synthesize theGraphView=_theGraphView;
Now in the setter, I set the current controller as the dataSource (aka the delegate):
-(void) setTheGraphView:(GraphView *)theGraphView
{
_theGraphView=theGraphView;
self.theGraphView.dataSource=self;
}
I also set the controller as the delegate in prepareForSegue (one of the things I tried while looking for a fix):
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([segue.identifier isEqualToString:@"GraphViewController"])
{
self.theGraphView.dataSource=self;
}
}
Finally, I implement the required method:
-(CGFloat)yValueForGraphView:(GraphView *)sender usingXval:(CGFloat)xVal
{
CGFloat test=51.40; //just to test
return test;
}
And the output I'm getting from my test NSLog in graphView's drawRect is:
2012-10-25 20:56:36.352 ..[2494:c07] first, y value is: 6.000000
2012-10-25 20:56:36.354 ..[2494:c07] now the y value now is: 0.000000
This should be returning 51.40 via the dataSource, but it is not. I can't figure out why! Driving me crazy, it seems like I've done everything right. But the delegate method is not getting called.
Is there some silly thing I am missing?
Additional info - diagram of controllers & GraphView:
