如何在Swift中獲得對應用程序委托的引用?最終,我想使用引用來訪問托管對象上下文。
3 回答

牛魔王的故事
TA貢獻1830條經驗 獲得超3個贊
另一個解決方案是正確的,因為它將為您提供對應用程序委托的引用,但這將不允許您訪問UIApplication的子類添加的任何方法或變量,例如托管對象上下文。要解決此問題,只需向下轉換為“ AppDelegate”或您的UIApplication子類碰巧被調用的任何東西。像這樣:
Swift 3.x(與Xcode 8一起引入)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let aVariable = appDelegate.someVariable
Swift 1.2-2.x(Xcode 6.3引入)
let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let aVariable = appDelegate.someVariable
斯威夫特<1.2
let appDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let aVariable = appDelegate.someVariable
- 3 回答
- 0 關注
- 464 瀏覽
添加回答
舉報
0/150
提交
取消