Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why am I getting a retain cycle from passing weak self in to a static function's closure?

My AchievementViewController does not get released from memory unless I comment out the function below

    NetworkConnection.achievementList(for: -1) { [weak self] response in
        guard let sections = response.object as? [AchievementListSection] else {
            return print("Network failure")
        }
        self?.sections = sections
        self?.configureCollectionView()
    }

The definition for this function is below where at present we just use a delayed async call to send a stubbed response.

static func achievementList(for identifier: Int64, responseHandler: RequestResponseClosure?) {
    let stubResponse = ResponseObject(object: AchievementListSection.exampleList as NSArray, code: .success)
    let randomDelayMilliseconds = Int(arc4random_uniform(1000))
    DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(randomDelayMilliseconds)) {
        responseHandler?(stubResponse)
    }
}

Where exactly is self being retained to create a cycle here? It's passed in to the NetworkConnection closure as a weak reference and in turn when this closure is passed to DispatchQueue I would expect it to release after the delay has passed.

like image 224
Declan McKenna Avatar asked Dec 10 '25 11:12

Declan McKenna


1 Answers

try comment this line

self?.configureCollectionView() 

mb it's the problem, because [weak self] is enough for fix retain in this closure

like image 179
Kstin Avatar answered Dec 12 '25 07:12

Kstin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!