Daily iOS
Memory and ARC

unowned crash scenario

This code, which loads an image asynchronously in a UITableView cell, crashes now and then. Under what condition does it crash, and why?

final class ImageCell: UITableViewCell {
    func load(_ url: URL) {
        loader.fetch(url) { [unowned self] image in
            self.imageView?.image = image
        }
    }
}
How would an interviewer hear this answer? You'll see whether they'd move on, dig in, or say no, and which sentences would trip you up. Your score doesn't change.
See the short answer

If the cell is deallocated before the network response arrives (the table view discards it, or the screen is closed), unowned self points at a dead object and traps the moment it's accessed. The closure can outlive self, and unowned assumes the opposite.

Share a question