[問題] 關於不同class 共用變數

作者: herbacin (herbacin)   2017-01-16 13:22:39
請問各位
假設我有多個viewcontroller, 每個viewcontroller都想
共用某個物件, 例如玩家資訊User Class,
那User Class一般是否都會寫在
AppDelegate.swift裡面呢?
例如 :
AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
var user = User()
}
當B Class要使用的時候
let app = UIApplication.shared.delegate as! AppDelegate
let player = app.user
一般是否都是這樣的使用呢?
因為AppDelegate這要是管理app生命週期, 才會想是否可以寫在這
謝謝
作者: tentenlee (天天)   2017-01-16 13:24:00
在宣告class外面那層宣告變數就是全域變數了
作者: darktt (小朱)   2017-01-16 14:47:00
不要將要保存放在 AppDelegate 中,這是不合物件導向規則的,你還有UserDefaults可以放資料,不然就是開一個單例的物件來保存暫時的資料
作者: herbacin (herbacin)   2017-01-16 15:13:00
我希望可以存在記憶體裡面, 因為其他viewController都有可能被釋放
作者: tkdmaf (皮皮快跑)   2017-01-16 16:03:00
你可以寫個struct用靜態呼叫。也是個方法。
作者: herbacin (herbacin)   2017-01-16 16:25:00
了解 謝謝喔
作者: bigbearlazir (肥宅)   2017-01-16 18:38:00
singleton instance不就是在記憶體上嗎singleton instance不等於viewcontroller
作者: gundam00 (傻那駕駛中)   2017-01-17 00:05:00
剛好最近也要用到singleton https://goo.gl/C5xa4e 這篇教你如何用最簡單的方式寫出singleton的class
作者: a26364177 (偉霖)   2017-01-18 01:47:00
Singleton

Links booklink

Contact Us: admin [ a t ] ucptt.com