在 init() 之前或 init() 内部读取 UserDefaults
reading UserDefaults before init() or inside of init()
我在将 default_ip 从我的 UserDefaults 获取到 SocketManager 时遇到问题。
final class Service: ObservableObject{
let defaults = UserDefaults.init(suiteName: "group.com.Scheduled-countdown.settings")
let manager = SocketManager(socketURL: URL(string: "http://172.20.10.4:3000")!, config: [.log(false),.compress,.path("/ws")])
init(){
let default_ip = defaults?.string(forKey: "ip_adress") ?? "Nothing"
let ipString : String = "http://\(default_ip):3000"
//let manager = SocketManager(socketURL: URL(string: ipString)!, config: [.log(false),.compress,.path("/ws")])
print(ipString)
print(default_ip)
}
}
如果我在 init() 上面有 SocketManager,它会连接,但我不能有 default_ip 因为上面说
Cannot use instance member 'defaults' within property initializer;
property initializers run before 'self' is available
那么我该如何解决这个问题?
我也上传了视频来说明问题
https://www.youtube.com/watch?v=teqr20AnTVM
改用 lazy var 对我很有帮助。
final class Service: ObservableObject{
let defaults = UserDefaults.init(suiteName: "group.com.Scheduled-countdown.settings")
lazy var default_ip = defaults?.string(forKey: "ip_adress") ?? "Nothing"
lazy var ipString : String = "http://\(default_ip):3000"
lazy var manager = SocketManager(socketURL: URL(string: ipString)!, config: [.log(false),.compress,.path("/ws")])
init(){
print(ipString)
print(default_ip)
}
}
我在将 default_ip 从我的 UserDefaults 获取到 SocketManager 时遇到问题。
final class Service: ObservableObject{
let defaults = UserDefaults.init(suiteName: "group.com.Scheduled-countdown.settings")
let manager = SocketManager(socketURL: URL(string: "http://172.20.10.4:3000")!, config: [.log(false),.compress,.path("/ws")])
init(){
let default_ip = defaults?.string(forKey: "ip_adress") ?? "Nothing"
let ipString : String = "http://\(default_ip):3000"
//let manager = SocketManager(socketURL: URL(string: ipString)!, config: [.log(false),.compress,.path("/ws")])
print(ipString)
print(default_ip)
}
}
如果我在 init() 上面有 SocketManager,它会连接,但我不能有 default_ip 因为上面说
Cannot use instance member 'defaults' within property initializer; property initializers run before 'self' is available
那么我该如何解决这个问题?
我也上传了视频来说明问题 https://www.youtube.com/watch?v=teqr20AnTVM
改用 lazy var 对我很有帮助。
final class Service: ObservableObject{
let defaults = UserDefaults.init(suiteName: "group.com.Scheduled-countdown.settings")
lazy var default_ip = defaults?.string(forKey: "ip_adress") ?? "Nothing"
lazy var ipString : String = "http://\(default_ip):3000"
lazy var manager = SocketManager(socketURL: URL(string: ipString)!, config: [.log(false),.compress,.path("/ws")])
init(){
print(ipString)
print(default_ip)
}
}