简体   繁体   中英

Will this situation create a strong reference cycle?

public class somethingViewController{
    func viewDidLoad(){
        let contentImageView = UIImageView()
        let contentImageViewTapRecognizer = UITapGestureRecognizer(target: self, action: #selector(somethingViewController.tapped(_:)))
        contentImageView.addGestureRecognizer(contentImageViewTapRecognizer)
        let stackView = OAStackView(arrangedSubviews: [contentImageView])
        self.view.addSubview(stackView)
    }
    func tapped(sender: UITapGestureRecognizer){
        //tapped
    }
}

I don't think this is a strong reference cycle, but I may be wrong. The reason why I think it could be a strong reference cycle is because stackView points to contentImageView which points back to somethingViewController via its selector in the tap recognizer.

If it is a strong reference cycle, how do I solve the problem?

There is no strong cycle, there are no problems. In the target-action pattern , the control will not retain the target:

Control objects do not (and should not) retain their targets. However, clients of controls sending action messages (applications, usually) are responsible for ensuring that their targets are available to receive action messages. To do this, they may have to retain their targets in memory-managed environments. This precaution applies equally to delegates and data sources.

This means there are no strong reference from the gesture recognizer to the view controller.

The whole cycle:

self 
 ↳ self.view (strong)
    ↳ stackView (strong, via subviews)
       ↳ contentImageView (strong, via subviews)
          ↳ contentImageViewTapRecognizer (strong, via gestureRecognizers)
             ↳ self (**weak**, via target)

This will remain till your class is in navigation stack or till your class is alive I mean not destroyed. So, you may say it strong reference but not strong reference cycle . If you push or present another view controller on it then it is there in memory and it's fine. This is normal behavior. So, there is nothing wrong in it so you not need to solve anything.

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