My initial GameViewController
has a delegate property of a GameDelegate
. I'm setting this property in the AppDelegate
:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
//Set initial view controller
window = UIWindow(frame: UIScreen.main.bounds)
if let window = window {
let gameTracker = GameTracker()
let gameViewController = GameViewController()
gameViewController.delegate = gameTracker
window.rootViewController = gameViewController
window.makeKeyAndVisible()
}
return true
}
This only works since my delegate is strong:
class GameViewController: UIViewController{
var delegate: GameDelegate?
var gameScore: GameScore {
return (delegate!.gameScore)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
Using a weak delegate will cause the App to crash since delegate will be nil after the GameViewController
is presented.
My question is: Is this approach safe, and if not, how should it be done? I've read about delegates and it's recommend to keep it as a weak var to prevent a retain cycle. I'm not using Storyboards.