Skip to content

Instantly share code, notes, and snippets.

@TachibanaKaoru
Created December 11, 2018 21:34
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 TachibanaKaoru/fb65884b0050756d4559d7b2e77c1700 to your computer and use it in GitHub Desktop.
Save TachibanaKaoru/fb65884b0050756d4559d7b2e77c1700 to your computer and use it in GitHub Desktop.
Circular Reference async
class Person{
var name: String
init(name: String) {
print("--- init \(name) ---")
self.name = name
}
deinit {
print("--- deinit \(name) ---")
}
func normalHello(){
print("Hello, I am \(name)!")
}
// MARK: - Closure関連
private var keepingClosure:(()->Void)?
// これはescaping
private func keepAndDo(_ closure:@escaping (()-> Void)){
self.keepingClosure = closure
closure()
}
// これはnoescape(デフォルトは noescape)
private func justDo(_ closure: (()-> Void)){
closure()
}
// MARK: - Hello系
func strongHello(){
self.keepAndDo {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + 1.0,
execute: {
print("....\(self.name) [strong]")
})
self.normalHello()
}
}
func weakHello(){
self.keepAndDo { [weak self] in
self?.normalHello()
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + 1.0,
execute: {
print("....\(self?.name) [weak]")
})
}
}
func noescapeHello(){
self.justDo {
self.normalHello()
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + 1.0,
execute: {
print("....\(self.name) [noescape]")
})
}
}
func noescapeAndWeakHello(){
self.justDo {
self.normalHello()
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + 1.0,
execute: {[weak self] in
print("....\(self?.name) [noescape and weak]")
})
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment