Hello I am new to Cocoa programming and I met a problem about NSRectFill.
There is one button in the window, and the following is my AppDelegate.m file:
Take a look at apple's Drawing Guide
well you don't have any context, the system has no idea where you want to draw. if you want to draw on a view or an image you have to use a lockFocus / unlockFocus pair.
so if you have a view as an outlet called redView
[redView lockFocus];
[[NSColor redColor] set];
NSRectFill(NSMakeRect( 50,50,10,10));
[redView unlockFocus];
but this is a really poor model, you generally want your objects to draw themselves.
when a views drawRect: method is called you already have focus and don't need the lock unlock pair
Some background, applicationDidFinishLaunching:
is called at the launch of a program once the program is 'done' loading resources.
But at this point, there could be many windows and many views displayed by the application. Simply calling NSRectFill()
is not enough. The application wouldn't know where to draw said rectangle (is it in this window or that one? This NSView or that one). Even if there's only one window and it might seem obvious... there might be multiple NSViews displayed that you're unaware of.... and with computers you have to be very explicit with your commands.
The bottom line is: there is no 'context' established for where the drawing actions to occur. As d00dle points out, you should read up on Drawing Guide.
When an NSView's drawRect:
is called, a context (itself) has already been set/defined. You could draw directly from your delegate's applicationDidFinishLaunching:
but a 'context' needs to be defined.