【发布时间】:2017-05-19 11:58:18
【问题描述】:
我最初的GameViewController 有一个GameDelegate 的委托属性。我在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
}
这只有在我的代表很强大时才有效:
class GameViewController: UIViewController{
var delegate: GameDelegate?
var gameScore: GameScore {
return (delegate!.gameScore)
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
使用弱委托将导致应用程序崩溃,因为在呈现GameViewController 后委托将为零。
我的问题是:这种方法安全吗?如果不安全,应该怎么做?我已经阅读了有关代表的信息,建议将其保留为弱 var 以防止保留周期。我没有使用故事板。
【问题讨论】:
标签: ios swift delegates automatic-ref-counting