I currently have some code that does something like this (massively simplified, but enough to illustrate the point):
@property (weak) IBOutlet CustomViewClass *customView;
...
for (int i=0; i<iterations; i++) {
// Crunch some data (Up to ~200,000 operations)...
// Update view to represent where we are in the process:
[_customView setNeedsDisplay:YES];
}
Whenever I run the code for a given number of iterations, the custom views drawRect: method is only called one time, once all of the iterations have completed.
What I would like is for the view to be forced to be updated after every iteration, and to wait until the view has been redrawn before going onto the next iteration – but I cannot find anywhere in the documentation how to get it working as I would like!
I feel like if I could simply call drawRect: directly that would solve my problem but I know NSView does not allow this!
Could anybody point me in the right direction?
The lack of view updating isn’t even the biggest problem with your current approach. The biggest problem is that your application is hung until it finishes. The user cannot cancel (if you have even provided a Cancel button), tell the application to hide, do anything else in the application while the work proceeds, or quit the application.
The correct approach is to move the body of the loop to an NSOperation. You can do this either by subclassing NSOperation or by creating one with a block. Then, throw all the operations into a queue.
If what you’re doing in the loop can safely be run in parallel, then you should create a queue and use that one. If you need it to happen one operation at a time, use dependencies to chain each operation to the one before it. If it absolutely must happen on the main thread, you can use the main queue, but you should do the least amount on the main thread that you can safely get away with.
As work proceeds, run some code on the main thread/main queue that tells your view to
setNeedsDisplay:. Since the operations aren’t on the main queue (assuming you didn’t put them there), or at least are broken up, this can happen while work is ongoing.Further reading: