Re: How to set up a thread listening to performSelector: messages?
Re: How to set up a thread listening to performSelector: messages?
- Subject: Re: How to set up a thread listening to performSelector: messages?
- From: "Oleg Krupnov" <email@hidden>
- Date: Thu, 25 Sep 2008 19:24:51 +0300
Wow, it worked!
-performSelector:onThread:withObject:waitUntilDone: rules.
I don't know how I overlooked this method. Many thanks. :)
On Thu, Sep 25, 2008 at 7:12 PM, Ken Thomases <email@hidden> wrote:
> On Sep 25, 2008, at 10:53 AM, Oleg Krupnov wrote:
>
>> I actually have tried this. My code looks like this (is it correct?):
>>
>> @implementation Worker
>>
>> - (void)threadMain:(id)data
>> {
>> runLoop = [NSRunLoop currentRunLoop];
>> [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
>> while(true)
>> {
>> [runLoop run];
>> }
>> }
>>
>> - (void)processRequest:(id)sender
>> {
>> NSLog(@"hello");
>> }
>>
>> @end
>>
>> Then from the main thread I send:
>>
>> [[worker runLoop] performSelector:@selector(processRequest:)
>> target:worker argument:request order:0 modes:[NSArray
>> arrayWithObject:NSDefaultRunLoopMode]];
>>
>> This time the -[NSRunLoop run] method does not exit immediately.
>> However the problem is that processRequest is never called and the
>> -[NSRunLoop run] never exits.
>>
>> What can be wrong? Should it work like this at all?
>
> No, that's not how you do it. NSRunLoop is not thread-safe. That is, you
> can't message a run loop other than the current thread's.
>
> You should use -performSelector:onThread:withObject:waitUntilDone:. You
> send it to the object you want to message -- the one that implements the
> method matching the selector. You need to supply the NSThread object for
> the thread, which you can keep from the time when the thread was created.
> Or the thread in question can query +[NSThread currentThread] and stash
> that object somewhere shared. The "withObject:" parameter is an argument
> object which would be passed as an argument to the method, if the method and
> selector take an argument.
>
> Cheers,
> Ken
>
>
_______________________________________________
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