Where does drawRect: method get called?


#1

The drawRect: method seems to be a ‘system’ method - From Documentation,‘This method is called when a view is first displayed or when an event occurs that invalidates a visible part of the view. You should never call this method directly yourself’

Now, in the Hypnosister code, where exactly does a call to this method happen?
(Is it in the HypnosisterAppDelegate, [[self window] addSubview:view] OR in [self.window makeKeyAndVisible] or somewhere else(pg 126)?)

Also,if we override this method, what is to ensure that ‘our’ implementation of this method gets called and not the ‘iOS’ implementation?

Similar question on loadView: method (in next chapter) - where does that get called?


#2

The drawRect: method is declared by the UIView class, which also provides a default implementation for it.

So if you subclass the UIView class, that is, define a new class that inherits from the UIView class, and override the drawRect: method, then your implementation will be called automatically.

As for who calls it: Ask not who calls it, ask how you cause it to be called when you want your view to be redrawn. You get it called by invoking one of these methods on your view: setNeedsDisplay or setNeedsDisplayInRect:

If you are interested in learning more about this, then you should read the View Programming Guide for iOS.

For the loadView, you should read the View Controller Programming Guide for iOS.


#3

In addition to ibex’s comments the drawRect method is also called when the frame (the CGRect) is drawn.

I found this out when I initialized BNRLogo (my subclass of HypnosisView). I created a CGRect called logoRect to be used as the frame (this was my mistake).

Code from HypnosisterAppDelegate implementation

    CGRect logoRect;
    BNRLogo *logoView = [[BNRLogo alloc] initWithFrame];
    [view addSubview];

When I did this the BNRLogo’s drawRect method was never called.

The correct code should be:

    BNRLogo *logoView = [[BNRLogo alloc] initWithFrame:CGRectMake(0, 0, 100, 100)];
    [view addSubview];

Creating the CGRect within the initialization ensures it’s calling drawRect from your BNRLogo class.

Hope this helps!