WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

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)
    }

1      

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.

2      

Hacking with Swift is sponsored by Emerge

SPONSORED Why are Swift reference types bad for app startup time, and what’s the performance cost of protocol conformances? That’s just a couple of the topics you can learn about on the Emerge blog — written by the app performance experts behind Emerge’s advanced app optimization and monitoring tools, based on their experience of working at companies like Apple, Airbnb, Snap, and Spotify.

Find out more

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

Reply to this topic…

You need to create an account or log in to reply.

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.