2011-09-18 43 views
0

我在协议/委托方法在模型(GraphView)和控制器(GraphViewController)之间工作时遇到了一些麻烦。所述的NSLog在的drawRect:在GraphView.m告诉我,表达视图和控制器之间的协议和委托

可变表达保持值(在NSLog的证明viewDidLoad中这一点)。我错过了明显的东西吗?

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

你放置在任何NSLogs在'expressionForGraphView:'明白为什么**'tempString' **正在返回'nil'? – WrightsCS

+0

您的日志语句以何种顺序发生? (你可能需要添加更多的文本告诉他们。) –

+0

ViewController首先被调用,所以在ViewDidLoad上,我可以看到表达式有一个值 - 没有问题。但是,当调用GraphView drawRect时,NSLog为null。有关信息,graphView对象具有由ViewController调用的“setNeedsDisplay”方法。 – John67

回答

0

线索是方法名

- (void)viewDidLoad 

你设置委托前先查看已加载。因此,当drawRect被称为代表是nil

设置委托在相关的初始化方法或IB