0

I have an entity named Score , which represent a day wise score. This entity has two properties date: Double and score: Double . Here date is the midnight timestamp epoch of a day. I've followed this stackoverflow answer to add date as a unique constraint to this entity.

So my code looks like this:

    let dispatchGroup = DispatchGroup()
    
    var factor1: Double = 0
    var factor2: Double = 0
    var factor3: Double = 0
    
    dispatchGroup.enter()

    calculateFactor1(date: date) { score in
        factor1 = score
        dispatchGroup.leave()
    }
   
   dispatchGroup.enter()
   calculateFactor2(date: date) { score in
        factor2 = score
        dispatchGroup.leave()
   }

   dispatchGroup.enter()
    calculateFactor3(date: date) { score in
        factor3 = score
        dispatchGroup.leave()
   }
    
    dispatchGroup.notify(queue: .main) {
        let mainScore = factor1 + factor2 + factor3
        let scoreObject = Score(context: self.context)
        scoreObject.date = date
        scoreObject.score = mainScore
        
        do {
            try self.context.save()
            completion()
        }
        catch {
            completion()
        }
    }

but this code crashes on context.save with an error: Constraint unique violation: UNIQUE constraint failed: ZSCORE.ZDATE

How can I debug this?

SPS
  • 359
  • 3
  • 12
  • 1
    I wouldn’t use data as unique constraint. You can use a random UUID as primary key – cora Jul 20 '22 at 14:29
  • In my use case each day(date = midnight epoch) is assigned a score, hence making **date** as a unique property made sense to me. But i'm curious as how having a UUID will help solve this issue? – SPS Jul 20 '22 at 14:34
  • Il’ there is some useful info [here](https://www.hackingwithswift.com/books/ios-swiftui/ensuring-core-data-objects-are-unique-using-constraints) : basically, specifying a merge policy to the container. – Ptit Xav Jul 20 '22 at 15:24
  • Turn on Core Data debug logging and see what happens at an SQL level by adding this Run argument to you scheme `-com.apple.CoreData.SQLDebug 4` – Joakim Danielson Jul 20 '22 at 15:51
  • Have you checked to see if your `notify` closure gets called more than once? That would cause the problem you’re seeing. – Tom Harrington Jul 21 '22 at 18:37
  • Something is definitely amiss in the way you're using the dispatch group. You enter once but leave three times. That would cause a crash on its own. – Tom Harrington Jul 22 '22 at 00:01
  • My Bad on dispatch enters, missed adding those in the question, but in actual code number of enters = number of leaves – SPS Jul 26 '22 at 07:41

0 Answers0