I’m new to objective-c so bear with me. This seems pretty simple but I must be doing something wrong. In IB I created an object, called it AppController and then added an action titled makeView and two IBOutlets, btnMakeView and mainWin, then connected everything properly and wrote the class file from that.
In AppController.h I have this code:
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject {
IBOutlet NSWindow * mainWin;
IBOutlet id btnMakeView;
}
- (IBAction)makeView:(id)sender;
@end
in AppController.m this code:
#import "AppController.h"
#import "ViewController.h"
@implementation AppController
- (IBAction)makeView:(id)sender {
//declare a new instance of viewcontroller, which inherits fromNSView, were going to allocate it with
//a frame and set the bounds of that frame using NSMakeRect and the floats we plug in.
ViewController* testbox = [[ViewController alloc]initWithFrame:NSMakeRect(10.0, 10.0, 100.0, 20.0)];
//this tells the window to add our subview testbox to it's contentview
[[mainWin contentView]addSubview:testbox];
}
-(BOOL)isFlipped {
return YES;
}
@end
in ViewController.h I have this code:
#import <Cocoa/Cocoa.h>
@interface ViewController : NSView {
}
@end
and finally in ViewController.m I have this code:
#import "ViewController.h"
@implementation ViewController
- (id)initWithFrame:(NSRect)frame {
self = [super initWithFrame:frame];
if (self) {
// Initialization code here.
}
return self;
}
- (void)drawRect:(NSRect)rect {
// Drawing code here.
//sets the background color of the view object
[[NSColor redColor]set];
//fills the bounds of the view object with the background color
NSRectFill([self bounds]);
}
@end
It compiles fine, there are no errors but do not get an object, which I am assuming will be a rectangle, starting at x,y 10/10 and being 100×20. What am I doing wrong?
Does
mainWinrefer to a valid window? Other than that, your code works, though it could use some improvement. For example,ViewControlleris a view, not a controller, so it shouldn’t be named a controller.ViewControlleryou create. The memory management rules are very simple; read up on them.Try the following changes. First, rename
ViewControllertoRedView(orSolidColorViewor somesuch). You can do this very simply by refactoring: right-click the class name in the@interfaceor@implementationdeclaration and choose “Refactor…”.In RedView.m:
In AppController.m: