SgViTiNer
SgViTiNer

Reputation: 118

NSTimer can't start or run in a NSThread function?

I want to use NSTimer to run a functions per 20 seconds,but I put the NSTimer in a NSThread function.the code is like this:

-(void)func1
{
   [NSThread detachNewThreadSelector:@selector(func2)   
                         toTarget:self withObject:nil];
}
-(void)func2
{
   [NSTimer scheduledTimerWithTimeInterval:3 target:self          
    selector:@selector(func3) userInfo:nil repeats:YES];
}
-(void)func3
{
  //do something,but the function seems never be executed
}

So the problem is that the func3 is never executed by the NSTimer in func2.Some people say that the NSTimer only run in main thread.is it true??so Can't NSTimer start in a NSThread function?

Upvotes: 0

Views: 536

Answers (2)

Jeffery Thomas
Jeffery Thomas

Reputation: 42588

It looks to me like your thread is not doing anything. timers are scheduled to be check as part of a thread's run loop. If the thread is not running any code, then it will not go through it's run loop.

Think of it this way:

  • Start Thread
  • Begin Thread Run Loop
  • -func2
  • End Run Loop
  • Sleep Thread

You have scheduled a timer on a thread that goes to sleep right after you setup the timer. No run loop; no timer fires.


UPDATE

My response answers the question but doesn't give a solution. What is the end effect you wish to achieve?

Upvotes: 4

andykkt
andykkt

Reputation: 1706

You can add timer to current thread's runloop by

(void)addTimer:(NSTimer*)aTimer forMode:(NSString*)mode

EDIT:

Helpful link for you: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/Multithreading/CreatingThreads/CreatingThreads.html#//apple_ref/doc/uid/10000057i-CH15-SW25

Upvotes: 0

Related Questions