2014-08-30 23 views
2

我正在使用通過按下按鈕通過精靈生成器調用以下方法。「禁用」按鈕 - >方法,直到完成操作

- (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 

} 

正如你可以從評論中看到的,我試着運行一次。這很好,但如果用戶回到這個場景,它會被禁用,直到您重新啓動應用程序。 如何阻止這種方法從第二次執行到第一次完成。 我知道代碼很粗糙,我只是在這裏學習....

在此先感謝。

回答

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 
+0

你可以點我在正確的方向來讀點文學作品這一點。我只是看不到它。謝謝。 – user2800989 2014-08-30 21:28:05

+0

@ user2800989我添加了一個例子。 – nhgrif 2014-08-30 21:32:22

+0

謝謝你的回覆。它幫了很大忙。如果你有時間,我還有一個問題。而不是使用afterDelay,我怎麼才能讓它重置,只有當場景重新加載。即。如果用戶去了下一個場景並決定回到這個場景? – user2800989 2014-08-30 21:52:38

0

更簡單的方法是使用串行NSOperationQueue這樣(斯威夫特):

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") 
     } 
    } 
} 
+0

謝謝。我還沒有繼續前進。但我會明確地保留這個在我的筆記! – user2800989 2014-08-30 21:58:07

+0

是的,這是做這件事的時尚方式。 – augustzf 2014-08-30 22:00:04