ios - Core Data: Exclude a NSManagedObject in fetch request in swift -
i have entity named "student" stores data of students. mobile number of students must unique. have validated when inserts new entity of student in core data. facing problem when trying update existing student data returns same object updated. have nsmanagedbject of student , want exclude in fetch request.
here code:
let request = nsfetchrequest<nsfetchrequestresult>(entityname:"student") request.predicate = nspredicate(format:"mobile == %@", "1234567890") { let count = try context.count(for:request) } catch { print(error.localizeddescription) }
with above code getting 1 record when updating existing student
i have done using nspredicate 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 checked if updating 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 { let count = try context.count(for: request) if count > 0 { return true } else { return false } } catch { print(error.localizeddescription) } return true }
Comments
Post a Comment