swiftcore-dataasync-awaitswift6sendable

NSManagedObjectContext perform: Sending value of non-Sendable type


Swift 5 How to resolve warnings:

'Sending value of non-Sendable type '() throws -> ()' risks causing data races; this is an error in the Swift 6 language mode'

for this code:

import CoreData
class Model{
  func foo()async throws {
    let ctx = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType);
    //....
    try await ctx.perform{ // warning here
      if ctx.hasChanges {
        try ctx.save();
      }
    }
  }
}

Solution

  • I found a solution

    If you add a @Sendable the warning will disappear

    you need to read

    https://forums.swift.org/t/nsmanagedobjectcontext-perform-sending-value-of-non-sendable-type/80229

    func foo()async throws {
          let ctx = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType);
          //..
          try await ctx.perform{ @Sendable in // warning disappear
            if ctx.hasChanges {
              try ctx.save();
            }
          }
        }