Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

static function escaping closure in Dispatch block using in VC test leak but deinit call #13

Open
cillyfly opened this issue Jun 20, 2019 · 2 comments

Comments

@cillyfly
Copy link

Hi
when I use this framework to test does function has leak. Code is like below. test unit shows it has leak, but when I use deinit to test is the viewcontroller is free, the deinit function called. and when I check memory graph, it seems no leak. can you help me to figure out why the test unit shows leak?

Function define

struct SchoolModel{ }

extension SchoolModel{
  static func loadData(completion: @escaping ([String]) -> Void){
    DispatchQueue.main.async {
      completion([])
    } 
  }
}

Using in viewcontroller

import UIKit
 
class ViewController: UIViewController {
  
  var completeData:[String] = []
  override func viewDidLoad() {
    super.viewDidLoad()
    SchoolModel.loadData { (data) in
      self.completeData = data
    }
  }
  deinit {
    print("\(#function)")
  } 
}

Test code

import Nimble
import Quick
import SpecLeaks

@testable import LeakTry

class leakTest: QuickSpec {
  override func spec() {
    describe("") {
      let test = LeakTest {
        let vc = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "ViewController") as! ViewController
        return vc
      }
      describe("init") {
        it("must not leak") {
          expect(test).toNot(leak())
        }
      }
    }
  }
}
@leandromperez
Copy link
Owner

@cillyfly The problem is that the DispatchQueue.main.async is retaining the completion block (I don't know why!), and the block retains the VC.

You can see this if you put [weak self], the test will pass.
Now, why does the DispatchQueue is retaining the closure? I am not sure. Tomorrow I'll give it another try.

@cillyfly
Copy link
Author

Thanks waiting for you ~

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants