简体   繁体   中英

Will this situation create a retain cycle

My sample code like this (just a sample):

[self.view touchActionWithCompeletion:^(NSSting *text){
    self.label.text = text;
}];

The block is a parameter of a method, the method is a instance method of self.view , then I access self in block. If self.view is a strong property, will this situation create retain cycle? And will self.view strong reference the block?

Adding my comment above as answer, after testing the code myself to confirm the logic I mentioned,

I think it should not, dead lock ( I mean memory leak, two strongly held objects holding the reference to each other and never being de-allocated hence I mentioned deadlock) will happen only if you pass a strong reference of an object to the block (in this case self) and then the passed object holds a strong reference to block itself (directly or indirectly).

Hoping that method touchActionWithCompeletion will not save the block passed to it with a strong reference this should not result in a retain cycle

EDIT:

Tested your code and deinit gets called as expected. Here is what I tried,

class MyView : UIView {
    func touchActionWithCompeletion(block :(NSString)->()) {
        block("abcd");
    }
}

class ThirdViewController: UIViewController {
    var myViewInstance = MyView()
    @IBOutlet var c: UITextField!

    override func viewDidLoad() {
        super.viewDidLoad()
        self.myViewInstance.touchActionWithCompeletion { (abcd) in
            self.c.text = abcd as String
        }
    }

    deinit {
        print("deinit called")
    }
}

As expected deinit called.

Only thing to notice here, method touchActionWithCompeletion will not store the block passed to it with strong reference. It simply executes it. So my answer above holds true in this case.

EDIT 2:(Clarifying my statement in answer)

I happened mention the passed object holds a strong reference to block itself (directly or indirectly) I guess I need to explain why I mentioned indirectly .

Consider this case, Deadlock will happen if View holds a strong reference to the block passed to its method. Though the strong object passed here to the block is self and self does not hold the reference to block directly, it still result in deadlock if View holds a strong reference to block.

Reason Self - holds a strong reference -> View - holds a strong reference -> Block - holds a strong reference -> Self

Hence deadlock. Though self does not hold the block directly, because it holds the block indirectly, hence deinit on self will not be called. Hence I happened to mention the passed object holds a strong reference to block itself (directly or indirectly)

Hope it helps

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM