Sorry about the long post, BUT I am back on this project, although I could probably change the title to "How do I access my models ivars from my NSView drawRect method"
To simplify my project, I am now just trying to draw a rectangle from 4 numbers in textfields (xorigin, yorigin, width and height). I have started from scratch using robbieduncan's advise. Here is what I have done so far.
I created a MODEL class called Model which inherits from NSObject. It has 4 integer instance variables (x, y, h, w) and each has a setter and getter method.
My VIEW in Interface Builder has 4 text fields (x,y,width,height), a button to trigger the drawing of the rectangle and a custom view.
My CONTROLLER is a class called Controller which inherits from NSObject. The controller .h is...
Code:
//Controller.h
#import <Cocoa/Cocoa.h>
#import "Model.h"
@interface Controller : NSObject
{
IBOutlet NSTextField* fieldX;
IBOutlet NSTextField* fieldY;
IBOutlet NSTextField* fieldW;
IBOutlet NSTextField* fieldH;
IBOutlet NSView *mainView;
Model *theModel;
}
- (IBAction) draw: (id) sender;
@end
And the controller .m is...
Code:
//Controller.m
#import "Controller.h"
@implementation Controller
- (void) awakeFromNib
{
NSLog (@" awakeFromNib has started");
theModel = [[Model alloc] init];
}
- (IBAction) draw: (id) sender;
{
NSLog (@" draw has started");
NSLog (@"x=%i - y=%i - w=%i - h=%i", fieldX.integerValue, fieldY.integerValue, fieldW.integerValue, fieldH.integerValue);
[theModel setX: [fieldX integerValue]];
[theModel setY: [fieldY integerValue]];
[theModel setW: [fieldW integerValue]];
[theModel setH: [fieldH integerValue]];
NSLog (@"tMx=%i - tMy=%i - tMw=%i - tMh=%i", [theModel x], [theModel y], [theModel w], [theModel h]);
[mainView setNeedsDisplay:YES]; // Invalidate the mainView area, so it will get redrawn
NSLog (@" draw has ended");
}
@end
Finally, I have a class called subView which inherits from NSView. It contains the 2 methods that Xcode puts in there. The drawRect: method is...
Code:
- (void)drawRect:(NSRect)rect
{
// Drawing code here.
NSLog (@" start drawRect");
// Draw the bounds of the View
NSRect bounds = [self bounds];
[[NSColor redColor] set];
[NSBezierPath strokeRect: bounds];
NSLog (@" end drawRect");
}
and according to my NSLogs, all methods are getting called and the CONTROLLER is talking to the MODEL, the drawRect is drawing the bounds...Everything works! My next step is to draw the rectangle using the ivars in my model, but when I try to put...
Code:
NSRect myRect = NSMakeRect ([theModel x], [theModel y], [theModel w], [theModel h]);
[[NSColor redColor] set];
[NSBezierPath strokeRect: myRect];
Xcode says "error: 'theModel' undeclared (first use in this function).
What do I need to do to have my drawRect method by able to access the instance variables from theModel???