Block retain cycles in Swift?

前端 未结 3 874
青春惊慌失措
青春惊慌失措 2020-12-12 15:11

Traditionally in Objc, we do weakSelf to prevent additional retain count for blocks.

How does swift internally manage retain cycles that occur in blocks for Objc?

3条回答
  •  眼角桃花
    2020-12-12 15:49

    As described above there are 2 possibilities to avoid retain cycles in Swift and these are weak and unowned as described below:

    var sampleClosure = { [unowned self] in
        self.doSomething()
    }
    

    where the self never can be nil.

    var sampleClosure = { [weak self] in
        self?.doSomething()
    }
    

    where self need to be unwrapped using ?. Here there is a important observation to do, if there are more instructions that use self and can be share the results etc, a possible correct way can be:

    var sampleClosure = { [weak self] in
        if let this = self{
           this.doSomething()
           this.doOtherThings()
        }             
    }
    

    or

    var sampleClosure = { [weak self] in
        guard let strongSelf = self else{
           return
        }
        strongSelf.doSomething()
        strongSelf.doOtherThings()             
    }
    

提交回复
热议问题