我正在使用一个C程序,尝试在我的iOS应用程序中使用它,并且尽可能少地进行修改。C程序对一组输入执行大量计算。
在iOS端,我使用以下代码创建一个线程来运行计算,并在完成时有一个报告机制(目前,它在完成时更新UILabel os "testLabel“):
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), ^{
char *testChar = startProgram( nx, ny, nz ); // this is where I call the C program
dispatch_async(dispatch_get_main_queue(), ^{
NSString *tempString = [[NSString alloc]initWithCString: testChar ];
testLabel.text = tempString;
[tempString release];
});
});这似乎起作用了,我得到了我的结果,并且我的UI保持响应。
但是,我希望在计算进行时从C例程返回到UI,以便获得状态并递增地传回一些数据。
所以我的C程序应该是这样的:
char* startProgram( int nx, int ny, int nz )
{
setupEverything(); // this is just pseudo code for clarity
for( int i = 0; i < nz; i++ )
{
doMajorCalculations();
reportBackToUI( someResults ); // This is what I would LIKE to do
}
}我在这里看到了一个关于传递"self“的帖子,但我不认为上面传递的"self”会是我的类"self“。此外,我尝试了一下,在C端得到了一个错误,说它不能识别类型"id“。我将"id“的类型改为类名,它告诉我参数是错误的。
有什么最好的实现方式的想法吗?
谢谢你的帮助。
发布于 2011-05-10 22:31:31
也许您想要的是有一个块作为回调,用于将部分结果报告给调用者。如下所示:
char* startProgram( int nx, int ny, int nz, void(^reportBackToUI)(int) )
{
setupEverything(); // this is just pseudo code for clarity
for( int i = 0; i < nz; i++ )
{
doMajorCalculations();
reportBackToUI( someResults ); // This is what I would LIKE to do
}
}然后,客户端可以使用如下命令调用startProgram:
return startProgram(42, 12, 20, ^(int someResults) {
dispatch_async(dispatch_get_main_queue(), ^{
// Update UI in some way.
});
});这样,您的代码将不依赖于客户端做什么或如何做,并使用进度回调。这也是一个很好的依赖注入。
如果使用块是不可能的(模型代码可能需要纯C才能在其他平台上工作?)然后,您可以将该块切换为函数指针。
https://stackoverflow.com/questions/5951244
复制相似问题