Core Data unique attributes

后端 未结 7 1346
眼角桃花
眼角桃花 2020-12-02 10:01

Is it possible to make a Core Data attribute unique, i.e. no two MyEntity objects can have the same myAttribute?

I know how to enforce this programatically, but I\'m

7条回答
  •  自闭症患者
    2020-12-02 10:33

    You just have to check for an existing one :/

    I just see nothing that core data really offers that helps with this. The constraints feature, as well as being broken, doesn't really do the job. In all real-world circumstances you simply need to, of course, check if one is there already and if so use that one (say, as the relation field of another item, of course). I just can't see any other approach.

    To save anyone typing...

    // you've download 100 new guys from the endpoint, and unwrapped the json
    for guy in guys {
        // guy.id uniquely identifies
        let g = guy.id
        
        let r = NSFetchRequest(entityName: "CD_Guy")
        r.predicate = NSPredicate(format: "id == %d", g)
        
        var found: [CD_Guy] = []
        do {
            let f = try core.container.viewContext.fetch(r) as! [CD_Guy]
            if f.count > 0 { continue } // that's it. it exists already
        }
        catch {
            print("basic db error. example, you had = instead of == in the pred above")
            continue
        }
        
        CD_Guy.make(from: guy) // just populate the CD_Guy
        save here: core.saveContext()
    }
    or save here: core.saveContext()
    

    core is just your singleton, whatever holding your context and other stuff.

    Note that in the example you can saveContext either each time there's a new one added, or, all at once afterwards.

    (I find tables/collections draw so fast, in conjunction with CD, it's really irrelevant.)

    (Don't forget about .privateQueueConcurrencyType )

    Do note that this example DOES NOT show that you, basically, create the entity and write on another context, and you must use .privateQueueConcurrencyType You can't use the same context as your tables/collections .. the .viewContext .

    let pmoc = NSManagedObjectContext(concurrencyType: .privateQueueConcurrencyType)
    pmoc.parent = core.container.viewContext
    do { try pmoc.save() } catch { fatalError("doh \(error)")}
    

提交回复
热议问题