Is it safe to call [subview setNeedsDisplay] inside [superview drawRect:]?

214 views Asked by At

I'm using UIGraphicsGetImageFromCurrentContext inside drawRect and setting a subview's property to the returned UIImage. This ends up triggering setNeedsDisplay in the subview.

Can this have any side effects?

Basically, will the subview always have its drawRect method called if setNeedsDisplay was called within the superview's drawRect method? Or would the subview be considered "already displayed", meaning no update will take place?

1

There are 1 answers

0
aleclarson On

From the mailing list: http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01697.html

If you call setNeedsDisplay: from within drawRect:, the flag will be set, but as soon as drawRect: returns, it will be cleared again. Therefore, when the time arrives, the flag is clear and drawRect: is not called again.

-drawRect should only be used for drawing. Resizing, repositioning, and adding or removing subviews absolutely should not be done in drawRect:. Incorrect behavior will likely result. The AppKit reasonably relies on the view hierarchy remaining constant while it is in the middle of drawing the view hierarchy.

Furthermore, do not call -display or variants or -drawRect from within drawRect: or you invite an infinite recursion and crash.

 

The above snippet is answering this question: http://lists.apple.com/archives/Cocoa-dev/2005/Jul/msg01693.html

Overview

I have an NSView (viewA) that manages multiple subviews. This view's drawRect contains code that positions and sizes all of its subviews accordingly and calls each of the subview's setNeedsDisplay:YES method. One of the subviews is also an NSView (viewB), and it also has multiple subviews.

Problem

If the window that contains viewA is resized, viewA's drawRect method is invoked, but for some unknown reason, viewB's drawRect method is not always invoked, despite the fact that viewA's drawRect method invokes viewB's setNeedsDisplay:YES method. The drawRect method associated with all of viewA's other subviews are invoked though.

Question

Can anyone suggest any reasons as to why viewB's drawRect method is not always called after its superview sends it a setNeedsDisplay message? Any ideas on what I'm doing wrong would be appreciated.