Search code examples
objective-cbackground-processosx-yosemitedrawrect

Draw the contents of an array modified in the background


I have a background thread that runs and modifies the contents of a NSMutableArray within an object. This takes a long time to run (several hours) and I periodically want to draw the contents of an array within the drawRect of a NSView to check on progress and see the intermediate results.

My object has a protocol with a method called: didChange:

// How I start my background thread
[self performSelectorInBackground:@selector(startProcessing) withObject:nil];

- (void)startProcessing {
    myObject.delegate = self;
    [myObject start];
}

// My protocol implementation
- (void)myObjectDidChange:(myObjectClass *)sender {
    [myView setNeedsDisplay:YES];
}

// My View's drawRect (pseudo code)
- (void)drawRect {
    [myObject drawInContext:context];
}

All works, except that the NSMutableArray backing all this is being changed whilst the drawing takes place. How should I do this? Do I somehow pause the processing in the background thread whilst the update is taking place?

EDIT: This is the sort of display I am drawing (although much more complicated):

enter image description here

Any help appreciated.


Solution

  • I have done it using NSLock to lock the outer loop of the start and the drawInContext methods. I am still not sure if this is the best approach and will not accept this answer for a few days in case there is a better answer out there.

    - (void)start {
       for(int i=0; i < MAX; i++) {
          [self.updateLock lock];
          ....
          [self.updateLock unlock];
       }
    }
    
    - (void)drawInContext:(CGContextRef)context {
       [self.updateLock lock];
       ...
       [self.updateLock unlock];
    }