views:

20

answers:

1

Hey guys,

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.

+1  A: 
-(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
}
Marcelo Cantos
Meh. `NSObject` surely was the last place I'd have thought to look at. Thank you very much.
zneak
You might want to read the "Threading Programming Guide", which would have given you a clue.
JWWalker
@JWWalker: Perhaps you intended it as a light-hearted jibe but your comment comes across as insulting, which is quite uncalled for. I myself had no idea there was such a guide, and came across my knowledge by other means.
Marcelo Cantos
@Marcelo Cantos: I meant it as neither an insult nor a jibe, just information. @zneak implied that he didn't know where he would have found out about performSelectorOnMainThread, and is clearly new to threading (at least in Cocoa) so he should read the guide.
JWWalker
@JWWalker: Fair enough. The phrase, "would have given you a clue" sounded like an implied, "you don't have a clue," and without any facial cues, it's impossible to tell which meaning you intended.
Marcelo Cantos
Fine. Here's what I should have said: @zneak, you wonder how you should have found that method. When starting with a new class or area of Mac programming, it's a good idea to see whether there's a Guide. In this case, the "Threading Programming Guide" would have helped.
JWWalker
@JWWalker: In my mind this is more a run loop issue than a threading issue, so I didn't think about checking there. I'm actually a little surprised that the method is called `performSelectorOnMainThread` and not `performSelectorOnMainRunLoop`.
zneak