开发者

What's the good way to synchronize calls to a NSView?

开发者 https://www.devze.com 2023-01-06 07:06 出处:网络
I have a view that receives new data from a secondary thread. Every time it does, it should redraw itself. However, it doesn\'t play nice with the run loop, and after some time (it\'s non-deterministi

I have a view that receives new data from a secondary thread. Every time it does, it should redraw itself. However, it doesn't play nice with the run loop, and after some time (it's non-deterministic), I end up getting <Error>: kCGErrorIllegalArgument: CGSUnionRegionWithRect : Invalid region messages in the console.

I'm 开发者_运维技巧not sure what's the right way to synchronize the calls to [view setNeedsDisplay:YES] across threads; can you help me?

To clarify a little, thread B (actually a dispatch queue) gives new contents to a view by calling this:

-(void)setImageBuffer:(unsigned char*)buffer
{
    /* image handling stuff; thread-safe */

    [self setNeedsDisplay:YES]; // but this is not thread-safe
}

And then thread A, on which runs the run loop, should redisplay the view.


-(void)setImageBuffer:(unsigned char*)buffer
{
    /* image handling stuff; thread-safe */

    [self performSelectorOnMainThread:@selector(induceRedraw)
                           withObject:nil
                                      // Don't just copy this; pick one...
                        waitUntilDone:YES or NO];
}

-(void)induceRedraw
{
    [self setNeedsDisplay:YES]; // but this is not thread-safe
}


With GCD you don't need the extra proxy method:

dispatch_queue_t q = dispatch_get_main_queue();
dispatch_async(q, ^(void) {
  [self setNeedsDisplay: YES];
});
0

精彩评论

暂无评论...
验证码 换一张
取 消