我试图在Swift上的AppDelegate上使用静态变量,所以我可以为所有viewControllers设置/获取值
AppDelegate.swift
class AppDelegate: UIResponder, UIApplicationDelegate {
struct Static {
static var userId: String?
}
获得:
var userGuid: String = AppDelegate.Static.userId!
环境:
AppDelegate.Static.userId = "123456"
但不知怎的,我的静态var总是传递nil
可能会发生什么? THX
答案 0 :(得分:2)
为您的用户会话信息设置一个专用类会更清楚吗?
示例(假设正在使用Swift 2.0)
class SessionInfo {
var userId:String?
static let sharedInstance = SessionInfo()
}
然后
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
SessionInfo.sharedInstance.userId = "foobar"
return true
}
另一种观点
@IBOutlet weak var labelTop: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
labelTop.text = SessionInfo.sharedInstance.userId
}