Re: Making a Window Class Invocable from Any Thread
Re: Making a Window Class Invocable from Any Thread
- Subject: Re: Making a Window Class Invocable from Any Thread
- From: "Michael Ash" <email@hidden>
- Date: Tue, 4 Nov 2008 23:40:57 -0500
On Tue, Nov 4, 2008 at 6:10 PM, Charles Steinman <email@hidden> wrote:
> This sounds like it might be a good case for a proxy. You could create a small class that looks something like this:
>
> @implementation MyClass
> @synthesize targetWindow;
> - (void)forwardInvocation:(NSInvocation *)invocation {
> [invocation performSelectorOnMainThread:@selector(invokeWithTarget:) withObject:self.targetWindow waitUntilDone:NO];
> }
> @end
This is what I would recommend as well. This sort of thing is easy and
also very powerful, and it's a very useful technique to be able to
use.
I'll note that this example is not 100% complete. (I assume it wasn't
meant to be, which is fine, I just want to mention the missing pieces
in case people have trouble finding them.) In addition to
-forwardInvocation:, a proxy must also implement
-methodSignatureForSelector: (otherwise the necessary information for
-forwardInvocation: to work will not be present) and should implement
-respondsToSelector: (not necessary, but code can be confused when an
object responds to a selector but claims not to).
Also, you'll want to do [invocation retainArguments] in
-forwardInvocation:, otherwise you'll get some painful memory
management bugs. NSInvocation doesn't retain its arguments by default
as an optimization. And lastly, using waitUntilDone:YES will allow the
caller to access the return value from the method, which can be very
useful.
> Not as efficient, so it wouldn't be good if these methods are being called a lot in a small period of time, but it's a lot less tedious than writing 50 dummy methods.
Not having measured them, performSelectorOnMainThread: is probably
also not particularly fast, so the additional overhead of forwarding
is unlikely to hurt.
I also want to caution the original poster, if he uses this technique,
not to simply assume that all threading problems have been solved. You
still have to be careful of the non-atomic nature of access to
multiple method invocations. As a contrived example, imagine two
threads doing this:
[windowProxy setTitle:[[windowProxy title] stringByAppendingString:@" more"];
You'd expect that if the title starts out as "foo", it will end up as
"foo more more". Depending on exactly how the threads execute,
however, it could end up being just "foo more" instead. This is not a
disastrous problem but needs to be kept in mind.
Mike
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden