Skip to content

Instantly share code, notes, and snippets.

@nrlnishan
Last active March 9, 2020 04:59
Show Gist options
  • Select an option

  • Save nrlnishan/8fde67360357dfe1a57decd642014732 to your computer and use it in GitHub Desktop.

Select an option

Save nrlnishan/8fde67360357dfe1a57decd642014732 to your computer and use it in GitHub Desktop.
Example showing no retain cycle
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()
}
}
}
@nrlnishan
Copy link
Author

nrlnishan commented Mar 9, 2020

how about number 37 ?

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment