如何在NSMutableSet上删除已应用的筛选器

时间:2017-07-20 15:16:48

标签: ios core-data swift3 nsmanagedobject 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()
      }

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

1 个答案:

答案 0 :(得分:0)

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

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