"禁用"按钮 - >方法直到操作完成

时间:2014-08-30 21:14:25

标签: objective-c cocos2d-iphone spritebuilder

我正在使用通过sprite builder按下按钮调用的以下方法。

- (void)method {

//static dispatch_once_t pred;    //
//dispatch_once(&pred, ^{         // run only once code below

[self performSelector:@selector(aaa) withObject:nil afterDelay:0.f];
[self performSelector:@selector(bbb) withObject:nil afterDelay:1.f];
[self performSelector:@selector(ccc) withObject:nil afterDelay:1.5f];
[self performSelector:@selector(ddd) withObject:nil afterDelay:4.f];
[self performSelector:@selector(eee) withObject:nil afterDelay:4.5f];

CCLOG(@"Received a touch");

//}); //run only once code above

}

你可以从评论中看到我尝试过运行一次。效果很好但是如果用户回到这个场景,它会被禁用,直到您重新启动应用程序。 如何阻止此方法第二次执行直到第一次完成。 我知道代码很粗糙,我只是在这里学习....

提前感谢。

2 个答案:

答案 0 :(得分:1)

添加一个BOOL实例变量,作为此操作是否发生的标志。方法一开始,请检查标志。如果需要执行,请设置标志。

添加另一个调用方法的performSelector:withObject:afterDelay:来重置标志。


@implementation SomeClass {
    BOOL _onceAtATime;
}

- (void)method {
    @synchronized(self) {
        if (!_onceAtATime) {
            _onceAtATime = YES;

            // do all the stuff you need to do

            [self performSelector:@selector(resetOnceAtATime) 
                       withObject:nil 
                       afterDelay:delay];
             // where delay is sufficiently long enough for all the code you
             // are executing to complete
        }
    }
}

- (void)resetOnceAtATime {
    _onceAtATime = NO;
}

@end

答案 1 :(得分:0)

更简单的方法是使用串行的NSOperationQueue(在Swift中):

class ViewController: UIViewController {

    let queue: NSOperationQueue

    required init(coder aDecoder: NSCoder) {
        queue = NSOperationQueue()
        queue.maxConcurrentOperationCount = 1
        super.init(coder: aDecoder)
    }

    @IBAction func go(sender: AnyObject) {
        if (queue.operationCount == 0) {
            queue.addOperationWithBlock() {
                // do the first slow thing here
            }
            queue.addOperationWithBlock() {
                // and the next slow thing here
            }
            // ..and so on
        }
        else {
            NSLog("busy doing those things")
        }
    }
}
相关问题