Junior — Middle
How is conflict resolution handled during data collisions in Swift?
sobes.tech AI
Answer from AI
In Swift, conflict handling during data collisions is often related to multithreading and synchronization of access to shared resources.
To prevent conflicts, the following are used:
- Dispatch Queues (GCD) — serial queues prevent simultaneous access to data.
- Locks and semaphores — for locking critical sections.
- Atomic operations — for simple data types.
- Core Data — when working with a database, a merge mechanism (merge policies), such as
NSMergeByPropertyObjectTrumpMergePolicy, is used to resolve conflicts when saving data.
Example of using a serial queue for synchronization:
let serialQueue = DispatchQueue(label: "com.example.serialQueue")
var sharedResource = 0
serialQueue.async {
sharedResource += 1
}
serialQueue.async {
sharedResource += 1
}
Thus, operations are executed sequentially, avoiding conflicts.
In Core Data, in case of conflict, a merge policy can be set:
context.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy