0

I tried to find the difference between the perform and performAndWait in NSManagedObjectContext. I used different context in different threads.

func addNewCell(name: String, id: String, time: Int64) {
            let newContext = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
            newContext.parent = context
            let cellEntity = NSEntityDescription.entity(forEntityName: "Cell", in: newContext)
            let newCell = Cell(entity: cellEntity!, insertInto: newContext)
            newCell.name = name
            newCell.id = id
            newCell.time = time
            do {
                try newContext.save()
                context.perform {
                    let t = Int.random(in: 0..<2)
                    sleep(UInt32(t))
                    do {
                        try self.context.save()
                    }
                    catch let err {
                        print(err)
                    }
                }
            } catch let err {
                print(err)
            }}

In the above code there was no difference when I switch between perform and performAndWait.

func addNewCell(name: String) {
    for i in 0..<10 {
        DispatchQueue.global(qos: .background).async {
            let id = UUID().uuidString
            let time = self.currentTime
            self.dataSource.addNewCell(
                name: name + "\(i)",
                id: id,
                time: time
            )
        }
    }

}

The above code is function that calls previous function in multiple threads. I Thought using performAndWait will give a sorted results but it didn't.

Can someone explain the difference between perform and performAndWait?

  • You'll want to check out the Apple documentation (https://developer.apple.com/documentation/coredata/nsmanagedobjectcontext). The difference is all about concurrency and knowing the order of operations being performed. – richardpiazza Sep 03 '20 at 15:00
  • See if this helps: https://stackoverflow.com/questions/32198678/behavior-differences-between-performblock-and-performblockandwait – WPK Oct 01 '20 at 07:48
  • The question and answer were using Objective-C so the API looked a bit different (performBlock vs perform, etc.) but the underlying concept for Core Data is the same. – WPK Oct 01 '20 at 07:55

0 Answers0