【发布时间】:2011-11-09 14:15:56
【问题描述】:
我很难弄清楚如何将这一切放在一起。 我在 mac 上有一个解谜应用程序。 你进入谜题,按下一个按钮,当它试图找到解决方案的数量时, 分钟移动等我想保持 UI 更新。 计算完成后,重新启用按钮并更改标题。
下面是按钮选择器的一些示例代码,以及求解函数: (请记住我是从 Xcode 复制/粘贴的,所以可能会丢失一些 {} 或 其他一些错别字.. 但它应该让你知道我想要做什么。
基本上,用户按下一个按钮,该按钮是 ENABLED=NO,调用函数来计算谜题。在计算时,请使用移动/解决方案数据更新 UI 标签。 然后一旦完成计算拼图,Button 为 ENABLED=YES;
按下按钮时调用:
- (void) solvePuzzle:(id)sender{
solveButton.enabled = NO;
solveButton.title = @"Working . . . .";
// I've tried using this as a Background thread, but I can't get the code to waitTilDone before continuing and changing the button state.
[self performSelectorInBackground:@selector(createTreeFromNode:) withObject:rootNode];
// I've tried to use GCD but similar issue and can't get UI updated.
//dispatch_queue_t queue = dispatch_queue_create("com.gamesbychris.createTree", 0);
//dispatch_sync(queue, ^{[self createTreeFromNode:rootNode];});
}
// Need to wait here until createTreeFromNode is finished.
solveButton.enabled=YES;
if (numSolutions == 0) {
solveButton.title = @"Not Solvable";
} else {
solveButton.title = @"Solve Puzzle";
}
}
需要在后台运行,以便更新 UI:
-(void)createTreeFromNode:(TreeNode *)node
{
// Tried using GCD
dispatch_queue_t main_queue = dispatch_get_main_queue();
...Create Tree Node and find Children Code...
if (!solutionFound){
// Solution not found yet so check other children by recursion.
[self createTreeFromNode:newChild];
} else {
// Solution found.
numSolutions ++;
if (maxMoves < newChild.numberOfMoves) {
maxMoves = newChild.numberOfMoves;
}
if (minMoves < 1 || minMoves > newChild.numberOfMoves) {
solutionNode = newChild;
minMoves = newChild.numberOfMoves;
// Update UI on main Thread
dispatch_async(main_queue, ^{
minMovesLabel.stringValue = [NSString stringWithFormat:@"%d",minMoves];
numSolutionsLabel.stringValue = [NSString stringWithFormat:@"%d",numSolutions];
maxMovesLabel.stringValue = [NSString stringWithFormat:@"%d",maxMoves];
});
}
【问题讨论】:
标签: iphone objective-c ios multithreading macos