如何删除 NSMutableSet 上应用的过滤器

How to remove applied filter on a NSMutableSet

我有两个实体学生和科目。学生可以有多个科目。我从 Student (NSManagedObject) 获取 NSMutableSet 对象

 let studentSubjects = student?.mutableSetValue(forKey: "subjects")

现在我想检查一个科目是否已经属于该学生。为此,我像这样在 NSMutableSet 上应用过滤器

 let assignedSubjects = assignedSubjects.filtered(using: NSPredicate(format: "subject_title == %@", "Science"))

现在我正在检查计数是否 > 0 然后执行一些操作,否则想将主题分配给学生

 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()
      }

问题是它总是插入新记录而不是保存现有记录。

插入新对象的行是这一行:

    var subjectObject = NSManagedObject(entity: subjectEntity!, insertInto: context)

无论当前学生是否已经有相关科目,都会执行。修改您的代码如下:

 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()
      }