Jonathan Ribeiro
Jonathan Ribeiro

Reputation: 346

UNIQUE constraint failed: ZTEMPORADA.Z_PK

I am doing work on swift and CoreData, but I have a problem when performing "Time" relationship with "Temporada", where a team can have several seasons and one season is a team.

Class Time

import Foundation
import CoreData

@objc(Time)
class Time: NSManagedObject {

@NSManaged var nome: String
@NSManaged var temporada: NSSet

override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
    let entity:NSEntityDescription = CoreDataManager.getEntity("Time")
    super.init(entity: entity, insertIntoManagedObjectContext: nil)
}

class func entityDescription() -> (NSEntityDescription){
    let entity:NSEntityDescription = CoreDataManager.getEntity("Time")
    return entity
}

func salvar(){
    let context:NSManagedObjectContext = CoreDataManager.getContext()
    var error:NSError?

    if (!self.inserted) {
        context.insertObject(self)
    }

    context.save(&error)

    if (error != nil){
        NSLog(error!.description)
    }
}
}

Class Temporada

import Foundation
import CoreData

@objc(Temporada)
class Temporada: NSManagedObject {

@NSManaged var ano: NSNumber
@NSManaged var numeroJogos: NSNumber

//relacionamentos
@NSManaged var time: Time
@NSManaged var jogador_temporada: NSSet

override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) {
    let entity:NSEntityDescription = CoreDataManager.getEntity("Temporada")
    super.init(entity: entity, insertIntoManagedObjectContext: nil)
}

class func entityDescription() -> (NSEntityDescription){
    let entity:NSEntityDescription = CoreDataManager.getEntity("Temporada")
    return entity
}

func salvar(){
    let context:NSManagedObjectContext = CoreDataManager.getContext()
    var error:NSError?

    if (!self.inserted) {
        context.insertObject(self)
    }

    context.save(&error)

    if (error != nil){
        NSLog(error!.description)
    }
}    
}

CoreDataManager

 import Foundation
 import CoreData
 import UIKit

 class CoreDataManager {

class func getEntity(entidade: String) -> NSEntityDescription {
    let delegate = (UIApplication.sharedApplication()).delegate as! AppDelegate
    let context:NSManagedObjectContext? = delegate.managedObjectContext
    let description: NSEntityDescription = NSEntityDescription.entityForName(entidade, inManagedObjectContext: context!)!

    return description
}

class func getContext() -> NSManagedObjectContext {
    let delegate = (UIApplication.sharedApplication()).delegate as! AppDelegate

    return delegate.managedObjectContext!
}

class func getAllManagedObjectsFromEntity(entity: NSEntityDescription) -> (sucesso: Bool, objects: NSArray){

    let delegate = (UIApplication.sharedApplication()).delegate as! AppDelegate
    let context:NSManagedObjectContext? = delegate.managedObjectContext

    let request:NSFetchRequest = NSFetchRequest()
    request.entity = entity

    var error:NSError?
    var objects:NSArray? = context?.executeFetchRequest(request, error: &error)

    if(error == nil){
        return(true, objects!)
    }else{
        NSLog(error!.description)
        return(false, objects!)
    }
}
}

In my ViewController, I have two methods, one for saving a "Time" and another to make this relationship...

@IBAction func salvar(sender: AnyObject) {

    var time: Time  = Time(entity: Time.entityDescription(), insertIntoManagedObjectContext: nil)
    time.nome = "Cruzeiro Esporte Clube"
    time.salvar()

    NSLog("Time Salvo")
}

@IBAction func salvarTemporada(sender: AnyObject) {

    var time: Time?
    var temporada: Temporada = Temporada(entity: Temporada.entityDescription(), insertIntoManagedObjectContext: nil)
    temporada.ano = NSNumber(integer: 2017)
    temporada.numeroJogos = NSNumber(integer: 10)
    temporada.salvar()

    var retorno = CoreDataManager.getAllManagedObjectsFromEntity(Time.entityDescription())
    if (retorno.sucesso) {
        time = retorno.objects.objectAtIndex(0) as? Time
        NSLog("recuperado = \(time?.nome)")
    }
    temporada.time = time!
    temporada.salvar()
 }

But I get the following error

2015-08-23 14:36:46.718 Kickoff_CoreData[1230:37874] CoreData: error: (1555) UNIQUE constraint failed: ZTEMPORADA.Z_PK
2015-08-23 14:36:46.719 Kickoff_CoreData[1230:37874] Core Data: error: -executeRequest: encountered exception = error during SQL execution : UNIQUE constraint failed: ZTEMPORADA.Z_PK with userInfo = {
    NSFilePath = "/Users/jonathanribeiro/Library/Developer/CoreSimulator/Devices/79DFD839-4790-40C4-8E92-59EB9ADED5CD/data/Containers/Data/Application/1CEB63B6-3AA8-414D-810F-46EEDC910270/Documents/Kickoff_CoreData.sqlite";
    NSSQLiteErrorDomain = 1555;
}

Can anyone help me?

Upvotes: 7

Views: 2288

Answers (1)

Bernardo Santana
Bernardo Santana

Reputation: 454

I had a similar problem recently. I figured out that I was inserting an NSManagedObject in an NSManagedObjectContext twice and then trying to save it. I see you're calling twice temporada.salvar in the same method, and since the saving is actually asynchronous, it might be causing trouble. Hope it helps.

Upvotes: 10

Related Questions