1.oc为范例执行
class UserObj: NSObject {
var userName : String!//成员变量
var userPwd : String!//成员变量
static func sharedInstance() -> UserObj{ //成员静态函数
struct Singleton{
static var onceToken:dispatch_once_t = 0
static var single:UserObj?
}
dispatch_once(&Singleton.onceToken,{
Singleton.single = UserObj()
})
return Singleton.single!
}
}
调用:
let user = UserObj.sharedInstance()
user.userName = nameText.text
user.userPwd = pwdText.text
UserObj.sharedInstance().userName
2.swift中用法
class UserObj: NSObject {
var userName : String!//成员变量
class var sharedInstance: UserObj {
struct Singleton {
static let instance = UserObj()
}
return Singleton.instance
}
}
调用:
let user = UserObj.sharedInstance
user.userName = nameText.text
user.userPwd = pwdText.text
UserObj.sharedInstance.userName
原文链接:https://www.f2er.com/swift/323738.html