Skip to content

Instantly share code, notes, and snippets.

@robertmryan
Last active February 16, 2021 21:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save robertmryan/4395613b13d96a2d811f5b002f0aad1b to your computer and use it in GitHub Desktop.
Save robertmryan/4395613b13d96a2d811f5b002f0aad1b to your computer and use it in GitHub Desktop.
class A {
private var b = B(0)
private let lock = NSLock()
deinit {
NotificationCenter.default.removeObserver(self)
}
func changeB(_ i: Int) {
synchronized { b = B(i) }
}
func testB(_ k: Int) -> Bool {
synchronized { b.test(k) }
}
func addObserver() {
NotificationCenter.default.addObserver(forName: B.didUpdate, object: nil, queue: nil) { [weak self] notification in
let k = notification.userInfo!["k"] as! Int
self?.handleNotification(with: k)
}
}
}
// MARK: - Private utility methods
private extension A {
func handleNotification(with k: Int) {
print(testB(k)) // no synchronization needed, because `testB` does that for us
}
func synchronized<T>(block: () throws -> T) rethrows -> T {
lock.lock()
defer { lock.unlock() }
return try block()
}
}
class B {
private let b: Int
static let didUpdate = Notification.Name("B") // obviously, name this notification to reflect the functional intent, but let's define the notification in one place, to avoid risk of typos elsewhere
init(_ i: Int) {
b = i
}
func test(_ k: Int) -> Bool {
b == k
}
}
@alexcohn
Copy link

I am afraid that I did not express my use case clear enough. I will try to be more accurate to the actual case, but it's not what looks as a question on SO. I have forged a different version here.

The question is, lock.synchronized() at line 84 seems irrelevant. But then the whole purpose of lock seems irrelevant, too.

Thank you for your patience with these ignoramus questions.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment