Last active
February 16, 2021 21:35
-
-
Save robertmryan/4395613b13d96a2d811f5b002f0aad1b to your computer and use it in GitHub Desktop.
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
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 | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 oflock
seems irrelevant, too.Thank you for your patience with these ignoramus questions.