大编辑:我认为问题可以简化为-我如何运行corebluetooth并在后台线程中初始化CBCentralManager?谢谢!
我正在使用CoreBluetooth通过命令行运行一个客观的c ++应用程序,因此对象C部分需要显式调用runloop [请参见this]。 CoreBluetooth要求有一个活动的运行循环,以便执行回调。下面的代码在程序的开头调用runloop以使所有工作正常:
implementation.mm
// inside init method
// initialize bluetooth manager, must initialize before the runloop
self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
// start run loop
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
while(([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]))
{}
而且我可以从我的c ++ main方法进行异步调用:
main.cpp
int main() {
std::thread worker(do_cpp_things); // c++ things in background thread
run_objective_c_code(); // call objective c code using main thread
}
然而,使用这种方法,我的c ++部分必须在后台线程中运行。而目标C应用程序位于与我想要的相反的主线程中。因此,我尝试在目标C文件中创建一个新线程,然后调用该线程的当前运行循环:
implementation.mm
// start a new thread
-(void)startThread {
NSThread *A = [[NSThread alloc] initWithTarget:self selector:@selector(runTheLoop) object:nil]; //create thread A
[A start];
}
// call runloop while in new thread
-(void) runTheLoop {
// Commenting out initialization for the sake of simplicity before it terminates when trying to initialize the manager in this example
// self.centralManager = [[CBCentralManager alloc] initWithDelegate:self queue:nil];
NSRunLoop *runLoop = [NSRunLoop currentRunLoop];
// TERMINATES HERE
while(([runLoop runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]))
{}
}
但是这只是提早终止。不知道我的方法是否存在根本错误。再次-我想在后台线程中使用活动的runloop运行我的Objective-C代码,并在主线程中运行我的c ++代码。
谢谢!
我相信您是在要求c ++在后台运行的线程中运行。相反,只需按下C函数即可在后台运行
int main() {
std::thread worker(run_objective c function); // objective c in background thread
do_cpp_things; // call c++ things code using main thread
}
您仍然需要正确处理联接,否则可能会使您的应用程序无响应/崩溃