On May 26, 2009, at 8:53 PM, Ken Thomases wrote:

On May 26, 2009, at 1:27 PM, Jean-Daniel Dupas wrote:


Le 26 mai 09 à 20:15, Andreas Grosam a écrit :


What would you suggest is the preferred way to add a timer to a different running thread?


Normally, I would use:

 NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
 [runLoop addTimer:aTimer forMode:NSDefaultRunLoopMode];


However, this requires that it will be invoked from the context of the target thread. How do I get the runLoop for any other than the current thread?

NSRunLoop is not thread safe, so you don't get it. Even is it was possible, you would not be able to use it.

That said, CFRunLoop is thread safe.

You can retrieve it using - performSelector:onThread:withObject:waitUntilDone:modes passing a mutable object as argument (an MutableArray for example) which will be used to store the return value (your CFRunLoop).

- (void)retrieveCurrentRunLoop:(NSMutableArray *)array {
        [array addObject:(id)CFRunLoopGetCurrent()];
}

Bleah. If you're going to interact directly with another thread using -performSelector:onThread:..., don't ask it for its run loop and then manipulate that. Just tell it to install the timer on its own run loop. In that case, you can use NSRunLoop just fine.

Regards,
Ken



Thank you for your replies.

Yes, I thought it could work as Ken suggested. Now I'm going to try this:

- (void) runTimer:(NSTimer*)aTimer
{
    if ([NSThread currentThread] == self.thread) {
[[NSRunLoop currentRunLoop] addTimer:aTimer forMode:NSDefaultRunLoopMode];
    }
    else {
[self performSelector:@selector(runTimer:) onThread:self.thread withObject:aTimer waitUntilDone:NO];
    }
}



Regards
Andreas


_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

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:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to