I have a class User which needs to be updated every time a user opens the app
class User : NSObject, NSCoding {
var vehicles : [Vehicles]
var bankaccounts : [BankAccounts]
var friends : [Friends]
}
In my home screen ViewController, I have a function that gets the data from backend using 3 Alamofire requests. Finally, I save the data in UserDefaults. DispatchGroup was the first thing that came to my mind to implement this. Here is the code
func loadUserData {
var user = User()
let userDataDispatchGroup = DispatchGroup()
userDataDispatchGroup.enter()
AF.request(...).responseJSON {
//update the user.vehicles array
userDataDispatchGroup.leave()
}
userDataDispatchGroup.enter()
AF.request(...).responseJSON {
//update the user.bankaccounts array
userDataDispatchGroup.leave()
}
userDataDispatchGroup.enter()
AF.request(...).responseJSON {
//update the user.friends array
userDataDispatchGroup.leave()
}
userDataDispatchGroup.notify(queue: .main) {
let encodedData = NSKeyedArchiver.archivedData(withRootObject: user)
UserDefaults.standard.set(encodedData, forKey: "user")
}
}
But I am not clear about the thread-safety of my user object. Since it will be updated in three different callbacks, would thread safety be an issue here? If yes, what would be the best way to solve the issue? I was thinking of using DispatchSemaphore. But I am not sure if that's the correct approach.