multithreading - 在 osx 和 ios 的主线程上运行循环

标签 multithreading cocoa grand-central-dispatch macos-carbon runloop

我找不到任何关于做一些真正基本的事情的引用:我希望在主 UI 循环上有一个名为“forever”的方法。我很高兴能有一种方法来调用与 UI 刷新率同步的方法,或者通过传递自定义时间粒度,因为我并不需要它比每 50-100 毫秒更频繁地发生。 C++ (Carbon) 和 Objective C 的答案都很好,尽管我最终会在纯 C++ 应用程序中使用它。如果您还可以建议如何删除此计时器,那就太好了。

请检查评论以获取有关我想使用它的线程场景的进一步说明。

类似的东西

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

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

void execute() {
    // do something
}

};

最佳答案

通常,您会在应用程序委托(delegate)的 didFinishLaunchingWithOptions 方法中执行类似的操作。当您使用 ivar 保存 NSTimer 的当前实例时,您可以随时停止它。

@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];
  }

但是如果您只想检查另一个线程状态,则应该通过 block 使用回调。

如果你想从另一个线程在主线程上执行某些操作,你可以使用dispatch_get_main_queue:

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

关于multithreading - 在 osx 和 ios 的主线程上运行循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16776575/

相关文章:

django - 带有fastcgi和线程的Django

swift - 如何在 Swift 中创建自定义完成 block

cocoa - 核心基础与基础

xcode - 是否可以在 xcode 项目中访问 Unity 变量?

ios - 双击识别器不适用于 NSTimer 运行

c++ - 如何保证两个线程中的两个类写同一个变量线程安全?

c++ - 如何同步写入线程和读取线程之间的数据库访问?

objective-c - 每个 CALayer 是否都有自己的 CGContextRef?

ios - CFRunLoopPerformBlock 与 dispatch_async

ios - 使用NSOperationQueue同时执行两个后台任务