UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

SOLVED: project 5: whats the problem with strong reference cycling? it still works..

Forums > 100 Days of Swift

Hi, the first code is the guided code. the second code is with strong referencing; i removed [weak ac, weak self]. The app works with both codes so I wonder whats the problem with strong reference cycling?

Guided code:

@objc func promptForAnswer(){
        let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
        ac.addTextField(configurationHandler: nil)

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
            [weak self, weak ac] action in 
            guard let answer = ac?.textFields?[0].text else { return }
            self?.submit(answer)

        }
        ac.addAction(submitAction)
        present(ac, animated: true, completion: nil)
    }

After removing weak capture lists:

@objc func promptForAnswer(){
        let ac = UIAlertController(title: "Enter answer", message: nil, preferredStyle: .alert)
        ac.addTextField(configurationHandler: nil)

        let submitAction = UIAlertAction(title: "Submit", style: .default) {
             _ in 
            guard let answer = ac.textFields?[0].text else { return }
            self.submit(answer)

        }
        ac.addAction(submitAction)
        present(ac, animated: true, completion: nil)
    }

3      

The problem with strong references isn't that your code won't work, it's that you can create a retain cycle and thus a memory leak. If A has a strong reference to B and B also has a strong reference to A, then they can't be automatically deallocated and that memory will remain tied up until your program ends.

Check out the Swift docs on Automatic Reference Counting for more info.

4      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.