I have a BaseViewController which is subclassed by all other view controllers in my app.
I have some state variables which must be consistent across all view controllers, so I plan to write code for passing back-and-forth these state variables once in the BaseViewController. For this I'm providing a helper function pushStatefulViewControllerWithIdentifier() for forward passing and using StatePassBackDelegate for backward passing.
import UIKit
class BaseViewController: UIViewController, StatePassBackDelegate {
class State {
var connected = false
var loggedIn = false
}
var state = State()
weak var delegate: StatePassBackDelegate? = nil
// MARK: Lifecycle
override func viewWillDisappear(animated: Bool) {
super.viewWillDisappear(animated)
if self.isMovingFromParentViewController() == true {
delegate?.passBackState(state)
}
}
// MARK: StatePassBackDelegate functions
func passBackState(state: AnyObject) {
self.state = state as! State
}
// MARK: Helpers
final func pushStatefulViewControllerWithIdentifier(identifier: String) {
let vc = storyboard?.instantiateViewControllerWithIdentifier(identifier) as! BaseViewController
vc.state = state
vc.delegate = self
navigationController!.pushViewController(vc, animated: true)
}
}
protocol StatePassBackDelegate: class {
func passBackState(state: AnyObject)
}
- Do I have strong reference cycles here?
- Should I instead use the singleton pattern here?
Aucun commentaire:
Enregistrer un commentaire