开发者

How can I make the main thread waiting for some seconds and then call a method?

开发者 https://www.devze.com 2023-03-15 10:49 出处:网络
I\'m very new in Objective C programming and I started to program a simple exercise. I want my main() to call a method from a class and from that method to use performSelector:(SEL) withObject:afterD

I'm very new in Objective C programming and I started to program a simple exercise. I want my main() to call a method from a class and from that method to use performSelector:(SEL) withObject:afterDelay. The problem is that it do开发者_如何转开发esn't call the method, and it doesn't delay either. //main

int main (int argc, const char * argv[])
{
...
    State * state = [[State alloc] init];
    [state startTimer];
   ...
}

//State.m

-(void)complete{
    NSLog(@"The door is Open (OPENING ==> OPEN)");
    [door setState:[door openState]];
}

-(void)startTimer{
    NSLog(@"The timer has started on Opening state");
//    timer = [NSTimer scheduledTimerWithTimeInterval:30 target:self selector:@selector(complete) userInfo:nil repeats:NO];
//    [timer retain];
//    [timer fire];
//    [timer release];
    [self performSelector: @selector(complete) withObject:nil afterDelay:30];
}

I have modified a little the code, but is the same. It's not the problem in the rest of the code, but in the startTimer() method because it doesn't call the complete() method. If I use the NSThread (which is commented out) it will call it but still no delay. I have looked all over the places and I saw that for my purposes this is the best solution, but is not working for me. To get an idea of what it has to do the program, the state has to remain for 30 seconds on "OPENING" and then complete and set it to OPEN state.


performSelector:(SEL) withObject:afterDelay requires you to be using a run loop. In a normal application, the run loop is set up and runs automatically. In a command line program (such as yours) you would need to set up and run the run loop yourself. Example code here.

However, if you just want to delay your program for a bit and don't need to be doing anything else, it's simpler just to use the sleep() function.


performSelector will be invoked on the present run loop context(call insertion run loop context). If the run loop context is no more active when invocation has to happen things will not work.

Make sure that your calling run loop of calling thread is active. ---- may be I can understand better if you show more code from your main function.

Why thread solution is worked of you -- when you create thread it is get executed by the process --- so irrespective of the calling run loop secondary thread will be called in process scope.

0

精彩评论

暂无评论...
验证码 换一张
取 消