我在使用Model(GraphView)和Controller(GraphViewController)之间的协议/委托方法时遇到了一些麻烦。 GraphView.m中 drawRect:中的NSLog告诉我表达式是 null
变量表达式包含一个值(ViewDidLoad中的NSLog证明了这一点)。我错过了一些明显的东西吗?
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);
}
答案 0 :(得分:0)
线索在方法名称
中- (void)viewDidLoad
在设置委托之前已经加载了视图。因此,当drawRect
被调用时,委托是nil
。
在相关的初始化方法或IB
中设置委托