Last active
March 9, 2020 04:59
-
-
Save nrlnishan/8fde67360357dfe1a57decd642014732 to your computer and use it in GitHub Desktop.
Example showing no retain cycle
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| class SecondViewController: UIViewController { | |
| var someText = "" | |
| var controller: UIAlertController! | |
| var label = UILabel() | |
| override func loadView() { | |
| view = UIView() | |
| view.backgroundColor = .white | |
| } | |
| override func viewDidLoad() { | |
| super.viewDidLoad() | |
| let button = UIButton() | |
| button.setTitleColor(UIColor.black, for: .normal) | |
| button.setTitle("Show Alert", for: .normal) | |
| view.addSubview(button) | |
| button.translatesAutoresizingMaskIntoConstraints = false | |
| button.centerXAnchor.constraint(equalTo: self.view.centerXAnchor).isActive = true | |
| button.centerYAnchor.constraint(equalTo: self.view.centerYAnchor).isActive = true | |
| button.addTarget(self, action: #selector(onButtonTap), for: .touchUpInside) | |
| view.addSubview(label) | |
| label.translatesAutoresizingMaskIntoConstraints = false | |
| label.textColor = .black | |
| label.text = "Default Text" | |
| label.topAnchor.constraint(equalTo: button.bottomAnchor, constant: 16).isActive = true | |
| label.centerXAnchor.constraint(equalTo: button.centerXAnchor).isActive = true | |
| } | |
| @objc func onButtonTap() { | |
| let controller = UIAlertController(title: "Title", message: "Message", preferredStyle: .alert) | |
| controller.addAction(UIAlertAction(title: "Ok", style: .default, handler: { _ in | |
| self.fetchDataFromServer() | |
| })) | |
| self.present(controller, animated: true, completion: nil) | |
| } | |
| func fetchDataFromServer() { | |
| NetworkService.performRequest { | |
| self.someText = "Text has been changed" | |
| self.label.text = self.someText | |
| print(self.someText) | |
| } | |
| } | |
| deinit { | |
| print("SecondViewController Deallocated") | |
| } | |
| } | |
| class NetworkService { | |
| static func performRequest(completion: @escaping ()->()) { | |
| // Simulating Network Request | |
| DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 5) { | |
| completion() | |
| } | |
| } | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Since we do not create an instance of NetworkService and store it on SecondViewController class, the SecondViewController would be deallocated. I have updated the example with that case.