Created
January 15, 2017 12:57
-
-
Save owenzhao/e082cc3e1fce3284f0d76148c5531c06 to your computer and use it in GitHub Desktop.
queue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@IBAction func printHello(_ sender: Any) { | |
// 队列,以消息绑定为例 | |
if shouldWaitSwitch.isOn { | |
while true { | |
let isSuccess = WaitingTaskQueue.append(task: "你好!") | |
if isSuccess { break } else { continue } | |
} | |
if let _ = shouldWaitSwitch.actions(forTarget: WaitingTaskQueue.self, forControlEvent: .valueChanged) { // already set | |
return | |
} | |
shouldWaitSwitch.addTarget(WaitingTaskQueue.self, action: #selector(WaitingTaskQueue.dealingTasks), for: .valueChanged) | |
} | |
else { | |
print("你好!") | |
if let _ = shouldWaitSwitch.actions(forTarget: WaitingTaskQueue.self, forControlEvent: .valueChanged) { // if set | |
shouldWaitSwitch.removeTarget(WaitingTaskQueue.self, action: #selector(WaitingTaskQueue.dealingTasks), for: .valueChanged) | |
} | |
} | |
} | |
@IBOutlet weak var shouldWaitSwitch: UISwitch! | |
class WaitingTaskQueue { | |
private static var firstItemPosition = 0 | |
private static var queue:[String] = [] | |
private static var isLocked = false | |
@objc static func dealingTasks() { | |
guard !isLocked else { | |
return | |
} | |
isLocked = true | |
var relativePosition = 0 | |
while relativePosition < queue.count { | |
print("\(queue[relativePosition]), \(firstItemPosition + relativePosition)") | |
relativePosition += 1 | |
} | |
queue.removeAll(keepingCapacity: true) | |
firstItemPosition += relativePosition | |
isLocked = false | |
} | |
static func append(task:String) -> Bool { // is success | |
guard !isLocked else { | |
return false | |
} | |
queue.append(task) | |
return true | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment