gpt4 book ai didi

swift - 我的 UserDefaults 值在 Swift 中总是落后(并发/并行)

转载 作者:行者123 更新时间:2023-11-28 13:46:25 27 4
gpt4 key购买 nike

为了确保在我的整个应用程序中使用最新的应用程序配置设置值,我需要确保首先将最新的值写入 UserDefaults。

在我的 didFinishLaunchingWithOptions 中,我正在调用以下函数

DataService.run.fetchLatestAppConfigSettings()

我的 fetchLatestAppConfigSettings() 函数是:

func fetchLatestAppConfigSettings(){

REF_APPCONFIGSETTINGS.observeSingleEvent(of: .value, with: { (snapshot) in

let venueRadius = snapshot.childSnapshot(forPath: "venueRadius").value as! Double
self.defaults.set(venueRadius, forKey: VENUE_RADIUS)

let discoverRadius = snapshot.childSnapshot(forPath: "discoverRadius").value as! Double
self.defaults.set(discoverRadius, forKey: DISCOVER_RADIUS)


}) { (error) in
print("error \(error.localizedDescription)")
}


}//end func

以下 VC 使用 UserDefaults 中的值,但由于在执行以下代码时尚未写入最新值,因此该值始终落后。

func fetchVenues(forLocation: CLLocation, handler: @escaping (_ venuesLoaded: Bool) -> ()){

//radius value passed is not the latest
DataService.run.getAllVenues(deviceLocation: forLocation, radius: DataService.run.venueRadius) { (venues) in

self.venueArray = venues
self.filteredVenueArray = venues
self.tableView.reloadData()


handler(true)

if self.filteredVenueArray.count == 0{
self.emptyStateLabel.isHidden = false
} else {
self.emptyStateLabel.isHidden = true
}


}//end func

最佳答案

您的 firebase 调用是异步的,因此您需要在 firebase 调用完成后告诉所有感兴趣的人您的默认值已更改。最简单的方法是发布自定义通知。对更改感兴趣的每个人都应该收听通知。

//Make your custom notification
extension Notification.Name {
static let userDefaultsUpdated = Notification.Name("userDefaultsUpdated")
}

//Post the notification when you update defaults
NotificationCenter.default.post(Notification(name: .userDefaultsUpdated))

//Subscribe everywhere that needs to be interested in UserDefaults changes
let token = NotificationCenter.default.addObserver(forName: .userDefaultsUpdated, object: nil, queue: .main) { notification in
//Do stuff with new defaults here
}

关于swift - 我的 UserDefaults 值在 Swift 中总是落后(并发/并行),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55348329/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com