I have two entities Student and Subjects. Student can have multiple subjects. I am getting NSMutableSet object from Student (NSManagedObject)
let studentSubjects = student?.mutableSetValue(forKey: "subjects")
Now I want to check if a subject is already belongs to that student. For this I am applying filter on NSMutableSet like this
let assignedSubjects = assignedSubjects.filtered(using: NSPredicate(format: "subject_title == %@", "Science"))
Now I am checking if count is > 0 then do some action else want to assign the subject to the student
let subjectEntity = NSEntityDescription.entity(forEntityName: "Subject", in: context)
var subjectObject = NSManagedObject(entity: subjectEntity!, insertInto: context)
if assignedSubjects.count > 0 {
if let filteredItem = assignedSubjects.first as? NSManagedObject {
subjectObject = filteredItem
}
}
if assignedSubjects.count == 0 {
if let subjectsManagedObject = studentSubjects.allObjects as? [NSManagedObject] {
if subjectsManagedObject.count > 0 {
studentSubjects.add(subjectObject)
} else {
student.setValue(NSSet(object:subjectObject), forKey: "subjects")
}
try context.save()
}
} else {
try subjectObject.managedObjectContext?.save()
}
The problem is It is always inserting new records instead of saving existing records.
The line which inserts a new object is this one:
var subjectObject = NSManagedObject(entity: subjectEntity!, insertInto: context)
which is executed regardless of whether the current student already has the relevant subject. Amend your code as follows:
var subjectObject : NSManagedObject
if assignedSubjects.count > 0 {
if let filteredItem = assignedSubjects.first as? NSManagedObject {
subjectObject = filteredItem
}
}
if assignedSubjects.count == 0 {
let subjectEntity = NSEntityDescription.entity(forEntityName: "Subject", in: context)
subjectObject = NSManagedObject(entity: subjectEntity!, insertInto: context)
// I assume, following your example, you want to add a new subject with title "Science"....
subjectObject.setValue("Science", forKey: "subject_title")
if let subjectsManagedObject = studentSubjects.allObjects as? [NSManagedObject] {
if subjectsManagedObject.count > 0 {
studentSubjects.add(subjectObject)
} else {
student.setValue(NSSet(object:subjectObject), forKey: "subjects")
}
try context.save()
}
} else {
try subjectObject.managedObjectContext?.save()
}