Skip to content

Instantly share code, notes, and snippets.

@jsorge
Last active May 3, 2017 15:21
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 jsorge/fe51cbbc2450366fc43e895e1a091bdc to your computer and use it in GitHub Desktop.
Save jsorge/fe51cbbc2450366fc43e895e1a091bdc to your computer and use it in GitHub Desktop.
//: Playground - noun: a place where people can play
import UIKit
class VC {
var dataSource: DataSource?
func viewDidLoad() {
let items = dataSource?.numberOfItemsIn(section: 9) ?? -1
print("There are \(items) items")
}
deinit {
print("deinit on the VC")
}
}
class DataSource {
struct Hooks {
var numberOfSectionsIn: ((_: Int) -> Int?)?
}
var hooks: Hooks?
func numberOfItemsIn(section: Int) -> Int {
guard hooks?.numberOfSectionsIn?(section) == nil else { return hooks!.numberOfSectionsIn!(section)! }
return 99
}
deinit {
hooks = nil
print("deinit on the data source")
}
}
class Frame {
var dataSource: DataSource? = DataSource()
let itemCount = 100
init() {
var hooks = DataSource.Hooks()
// Right here I want to capture an unowned self
hooks.numberOfSectionsIn = numberOfSectionIn
// But if I pass in a closure with an unowned self, there's no problem
// hooks.numberOfSectionsIn = { [unowned self] (section) -> Int? in
// return self.itemCount
// }
dataSource?.hooks = hooks
}
func numberOfSectionIn(_ section: Int) -> Int? {
// The DataSource hook now has a strong reference to Frame
return itemCount
}
deinit {
dataSource = nil
print("deinit on the frame")
}
}
var frame: Frame? = Frame()
var vc: VC? = VC()
vc?.dataSource = frame!.dataSource
vc?.viewDidLoad()
vc = nil
frame = nil
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment