Created
September 15, 2016 09:49
-
-
Save desmondmc/070be8add6c7ccb54d56c86d0589f5fb to your computer and use it in GitHub Desktop.
An example of a retain cycle using swift blocks.
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
// | |
// ViewController.swift | |
// RetainCylceTests | |
// | |
// Created by Desmond McNamee on 15/09/16. | |
// Copyright © 2016 Teamplace. All rights reserved. | |
// | |
import UIKit | |
class ViewController: UIViewController { | |
override func viewDidLoad() { | |
super.viewDidLoad() | |
var counter: Counter? = Counter() | |
counter?.incrementCounter() | |
print("counter: \(counter!.count)") | |
counter = nil | |
} | |
override func didReceiveMemoryWarning() { | |
super.didReceiveMemoryWarning() | |
// Dispose of any resources that can be recreated. | |
} | |
} | |
class Do { | |
func something(closure: ()->Void) { | |
closure() | |
} | |
} | |
class Counter { | |
var count: Int = 0 | |
var closure: (()->Void)? | |
func incrementCounter() { | |
let doo = Do() | |
self.closure = { | |
// THIS CAUSES A RETAIN CYCLE! | |
self.count += 1 | |
} | |
doo.something(self.closure!) | |
} | |
deinit { | |
print("Yay!") | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment