在单独的线程/进程中运行音频引擎,从主线程发送和接收消息

时间:2015-09-14 14:02:36

标签: ios objective-c multithreading swift nsthread

我正在使用一个用C ++构建的独立音频引擎编写iOS应用程序。我们的想法是尽可能多地使用Swift编写应用程序,将音频引擎作为单独的线程或进程运行,然后让用户界面触发与音频引擎的通信。

如何最好地实现这一目标?

我的第一个尝试是添加一个处理触发相应C ++代码的中间Objective-C ++类(TestEngine)。这个Objective-C ++类我在Swift中这样启动:

// Initialize audio engine
let engine = TestEngine()

// Start engine in a new thread
NSThread.detachNewThreadSelector(NSSelectorFromString("startEngine"), toTarget: engine, withObject: nil)

TestEngine类如下所示:

@implementation TestEngine

- (void) startEngine {
    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(selectorMethod)
     name:@"testSelector"
     object:nil];

    NSLog(@"StartEngine done on thread:%@", [NSThread currentThread]);

}

- (void) selectorMethod {
    NSLog(@"This is selector, on thread %@", [NSThread currentThread]);
}

- (void)dealloc
{
    NSLog(@"Now deallocing");
}

@end

现在的问题是,在能够接收任何通知之前,该对象立即被释放。我也尝试过查看RunLoops,但是找不到任何简单(不是太低级别)的方法来向RunLoop添加观察者。关于如何在iOS上最好地设计这样的解决方案的任何想法?

1 个答案:

答案 0 :(得分:1)

我想这里有你的答案

引用Apple文档

  

常规通知中心在线程中发送通知   通知已发布。分布式通知中心   在主线程上发送通知。有时,您可能需要   要在特定线程上传递的通知   由您而不是通知中心确定。例如,如果   在后台线程中运行的对象正在侦听   来自用户界面的通知,例如窗口关闭,您   想在后台线程中收到通知   而不是主线程。在这些情况下,你必须抓住   通知,因为它们是在默认线程和重定向上传递的   他们到适当的线程。

相关问题