Rajat Jain
Rajat Jain

Reputation: 1022

Core Data: Exclude a NSManagedObject in fetch request in swift

I have an entity named "Student" which stores data of students. Mobile number of students must be unique. I have validated it when we inserts a new entity of student in core data. Now facing a problem when I am trying to update existing student data it always returns the same object which is to be updated. I have NSManagedbject of a student and I want it to exclude in my fetch request.

Here is my code:

let request = NSFetchRequest<NSFetchRequestResult>(entityName:"Student")
request.predicate = NSPredicate(format:"mobile == %@", "1234567890")
do {
     let count = try context.count(for:request)
 } catch {
       print(error.localizedDescription)
 }

With the above code I am always getting 1 record when updating existing student

Upvotes: 1

Views: 728

Answers (1)

Rajat Jain
Rajat Jain

Reputation: 1022

I have done this by using NSPredicate like below:

let predicate = NSPredicate(format:"NOT (self IN %@)",[arrayofNSManagedObjects])


public static func checkUniqueStudent(mobile:String,student:NSManagedObject? = nil) -> Bool {

    guard let context = DBManager.shared.managedObjectContext else { return true }

    let request = NSFetchRequest<NSFetchRequestResult>(entityName:"Student")

    let titlePredicate = NSPredicate(format: "mobile == %@", mobile)

    var predicateArray:[NSPredicate] = [
        titlePredicate,
    ]

    //here I checked if we are updating an existing record
    if student != nil {
        let studentPredicate = NSPredicate(format: "NOT (self IN %@)", [student!])
        predicateArray.append(studentPredicate)
    }

    let compoundPredicate = NSCompoundPredicate(type: .and, subpredicates: predicateArray)

    request.predicate = compoundPredicate

    do {
        let count = try context.count(for: request)

        if count > 0 {
            return true
        } else {
            return false
        }

    } catch {
        print(error.localizedDescription)
    }

    return true
}

Upvotes: 1

Related Questions