2017-10-06 05:34:29 +02:00
|
|
|
//
|
|
|
|
// BatchUpdates.swift
|
|
|
|
// DataModel
|
|
|
|
//
|
|
|
|
// Created by Brent Simmons on 9/12/16.
|
|
|
|
// Copyright © 2016 Ranchero Software, LLC. All rights reserved.
|
|
|
|
//
|
|
|
|
|
|
|
|
import Foundation
|
|
|
|
|
|
|
|
public typealias BatchUpdateBlock = () -> Void
|
|
|
|
|
|
|
|
public extension Notification.Name {
|
|
|
|
|
2017-10-07 20:56:22 +02:00
|
|
|
public static let BatchUpdateDidFinish = Notification.Name(rawValue: "BatchUpdateDidFinish")
|
2017-10-06 05:34:29 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
final class BatchUpdate {
|
|
|
|
|
2017-10-06 05:38:54 +02:00
|
|
|
static let shared = BatchUpdate()
|
|
|
|
|
2017-10-06 05:34:29 +02:00
|
|
|
private var count = 0
|
|
|
|
|
|
|
|
var isPerforming: Bool {
|
|
|
|
get {
|
|
|
|
return count > 0
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func perform(_ batchUpdateBlock: BatchUpdateBlock) {
|
|
|
|
|
|
|
|
incrementCount()
|
|
|
|
batchUpdateBlock()
|
|
|
|
decrementCount()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
private extension BatchUpdate {
|
|
|
|
|
|
|
|
func incrementCount() {
|
|
|
|
|
|
|
|
count = count + 1
|
|
|
|
}
|
|
|
|
|
|
|
|
func decrementCount() {
|
|
|
|
|
|
|
|
count = count - 1
|
|
|
|
|
|
|
|
if count < 1 {
|
|
|
|
|
|
|
|
if count < 0 {
|
|
|
|
assertionFailure("Batch updates count should never be below 0.")
|
|
|
|
count = 0
|
|
|
|
}
|
|
|
|
|
|
|
|
count = 0
|
|
|
|
postBatchUpdateDidPerform()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func postBatchUpdateDidPerform() {
|
|
|
|
|
2017-10-07 20:56:22 +02:00
|
|
|
NotificationCenter.default.post(name: .BatchUpdateDidFinish, object: nil, userInfo: nil)
|
2017-10-06 05:34:29 +02:00
|
|
|
}
|
|
|
|
}
|