Refactoring: find the real leak instead of sprinkling weak self
Task
What's wrong with this controller? Find the leaks and bugs, and explain where [weak self] is needed and where it isn't.
final class FeedViewController: UIViewController {
private let service = FeedService()
private var timer: Timer?
private var items: [Item] = []
private let tableView = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
service.onUpdate = { items in
self.items = items
self.tableView.reloadData()
}
timer = Timer.scheduledTimer(withTimeInterval: 30, repeats: true) { [weak self] _ in
self?.service.refresh()
}
service.load { [weak self] result in
guard let self else { return }
if case .success(let items) = result {
self.items = items
self.tableView.reloadData()
}
}
}
}
The rest of this answer, with code and interview follow-ups, is in the DevPrep app.
Read the full answer in DevPrep