Domanda

I can't find any reference on doing something that should be really basic: I'd like to have a method called "forever" on the main UI loop. I would be happy both with an way to call my method synced with the UI refresh rate, or by passing a custom time granularity, as I don't really need it to happen more often than every 50-100 ms. Both answers for C++ (Carbon) and Objective C are fine, even though I will eventually use it in a pure C++ application. If you could suggest also how to remove this timer, it would be great.

Please check the comments for a further explanation of the threading scenario where I want to use this.

something like

class MySyncedClass {
void start() {
    // start calling "execute" member function on main loop every N ms
}

void stop() {
   // stop calling "execute"
}

void execute() {
    // do something
}

};
È stato utile?

Soluzione

usually you do something like this in the application delegate in the method didFinishLaunchingWithOptions. When you use an ivar to save the current instance of NSTimer, you can stop it anytime.

@implementation AppDelegate {
    NSTimer *_timer;
}

- (void) start {
    _timer = [NSTimer scheduledTimerWithTimeInterval:0.2 target:self selector:@selector(execute) userInfo:nil repeats:YES];
}

- (void) stop {
    //reset timer
    if (_timer != nil) {
        [_timer invalidate];
        _timer = nil;
    }
}

- (void) execute {
    //do something
}

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
     [self start];
  }

but you should use a callback via block if you only want to check another threads status.

if you want to execute something on the main thread from another thread you can use dispatch_get_main_queue:

dispatch_async(dispatch_get_main_queue(), ^{
             //do something
         });

Altri suggerimenti

  1. Swift 3.0

    DispatchQueue.main.async(execute: { 
                        self._eventListTableView.reloadData()
                    })
    
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top