I'm having some trouble getting the protocol/delegate method to work between the Model (GraphView) and the Controller (GraphViewController). The NSLog in the drawRect: in GraphView.m tells me that expression is null
the variable expression holds a value (the NSLog in ViewDidLoad proves this). Am I missing something obvious?
GraphView.h
@class GraphView;
@protocol GraphViewDelegate
-(NSString *) expressionForGraphView:(GraphView *) requestor;
@end
@interface GraphView : UIView
{
id <GraphViewDelegate> delegate;
}
@property (assign) id <GraphViewDelegate> delegate;
@end
GraphView.m
#import "GraphView.h"
@implementation GraphView
@synthesize delegate;
- (void)drawRect:(CGRect)rect
{
NSString *expression = [self.delegate expressionForGraphView:self];
NSLog(@"%@", expression);
}
GraphViewController.h
#import <UIKit/UIKit.h>
#import "GraphView.h"
@interface GraphViewController : UIViewController <GraphViewDelegate>
{
GraphView *graphView;
NSString *expression;
}
@property (retain) IBOutlet GraphView *graphView;
@property (开发者_开发技巧retain) NSString *expression;
@end
GraphViewController.m
#import "GraphViewController.h"
@implementation GraphViewController
@synthesize graphView;
@synthesize expression;
-(NSString *) expressionForGraphView:(GraphView *) requestor
{
NSString *tempString;
if (requestor == self.graphView)
tempString = self.expression;
else
tempString = nil;
return tempString;
}
- (void)viewDidLoad
{
[super viewDidLoad];
self.graphView.delegate = self;
NSLog(@"%@", self.expression);
}
The clue is in the method name
- (void)viewDidLoad
The view has already loaded before you set the delegate. Therefore when the drawRect
was called the delegate was nil
.
Set up the delegate in the relevant initializer method or in IB
精彩评论