5

In Cocoa, when we want to redraw a view, we would send the view a setNeedsDisplay: message telling the view to redraw itself with a parameter of YES. I was wondering if there are any circumstances where you would want to send a view setNeedsDisplay:NO, such as multithreading environments, and if sending a view a setNeedsDisplay:YES, then setting it again immediately after with setNeedsDisplay:NO would make the view redraw itself. If there are no reasons to call setNeedsDisplay:NO, then why create such a tedious method, where they could instead implement something like [view redrawView]

TheAmateurProgrammer
  • 9,252
  • 8
  • 52
  • 71

2 Answers2

1

setNeedsDisplay:NO may be used in case you want to discard previously called setNeedsDisplay:YES. E.g. sometimes it is easier to mark all subviews as needing display and then run an algorithm to unmark some of them.

Olex
  • 178
  • 1
  • 4
-2

As you perhaps know, the display update is automatic (if necessary) at each pass through the normal event loop. You call setNeedsDisplay: in order to force a display update in between if it is necessary.

From the documentation of NSView:

Discussion
Whenever the data or state used for drawing a view object changes, the view should be sent a setNeedsDisplay: message. NSView objects marked as needing display are automatically redisplayed on each pass through the application’s event loop. (View objects that need to redisplay before the event loop comes around can of course immediately be sent the appropriate display... method.)

The boolean parameter to this function simply specifies if the entire bounds of the view in question is affected or not, not if some property "needsDisplay" is set to true or false. Thus, setNeedsDisplay: does indeed work pretty much like a "redrawView", only with the additional parameter.

Edit

The above was inspired from the same documentation:

flag
If YES, marks the receiver’s entire bounds as needing display; if NO, marks it as not needing display.

Mundi
  • 79,884
  • 17
  • 117
  • 140
  • 3
    This is largely incorrect. The event loop checks whether a view needs to be redrawn, as determined by `setNeedsDisplay:` having been called (it does indeed set a flag: `-[NSView needsDisplay]`). That method absolutely does not cause an immediate redraw, nor is every view necessarily redrawn on every pass. The forced drawing behavior you mention is provided by `-[NSView display]` and `-[NSView displayRect:]`. See http://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/CocoaViewsGuide/Optimizing/Optimizing.html#//apple_ref/doc/uid/TP40002978-CH11-112409 – jscs Sep 25 '12 at 16:47
  • Fair enough. I edited my answer and explained where the info comes from. – Mundi Sep 25 '12 at 20:01
  • 1
    @Mundi Unfortunately this doesn't exactly answer my question. I'm asking if there are any usage for `setNeedsDisplay:NO`. – TheAmateurProgrammer Sep 25 '12 at 23:53