How to check if there is duplicate data in coredata's entity when adding data

Viewed 29

I am learning core data, and I want to add data, before this, i want to check if there is repeated data in Backpack Entity, if there are duplicate values, return Bool to prompt the user. so write this function to get the number of repeated data, but may be the reason for the purple error is not effective, do not know how to solve...

purple error:Accessing StateObject's object without being installed on a View. This will create a new instance each time.

Help please...

    func RecheckingEquip() -> Bool {
    @FetchRequest(sortDescriptors: [NSSortDescriptor(keyPath: \Backpack.creatTime, ascending: false)],
                  predicate: NSPredicate(format: "equipedImage == %@", equips.imageName),
                  animation: .default) var backpackItems: FetchedResults<Backpack>

    let number = backpackItems.count

    if number == 0 {
        return false
    }
    return true
}

code

1 Answers

i think i know it, Let me answer myself this question

    func RecheckingEquip(context: NSManagedObjectContext) -> Bool {
    
    let entityForTableName = NSEntityDescription.entity(forEntityName: "EntityName", in: context)
    let fetchRequest = NSFetchRequest<NSFetchRequestResult>()

    let predicate = NSPredicate.init(format: "someAttribute == %@", someVariable)
    fetchRequest.predicate = predicate
    fetchRequest.entity = entityForTableName

    do {
        let arrData = try context.fetch(fetchRequest)

        if arrData.count > 0 {
            print("Record already exist")
            return true
        } else {
            return false
        }

    } catch {
        print(error.localizedDescription)
    }
    return false
}
Related