核心数据:在swift中的获取请求中排除NSManagedObject

时间:2017-07-26 08:37:21

标签: ios core-data swift3 nsmanagedobject nsfetchrequest

我有一个名为" Student"它存储学生的数据。移动学生人数必须是唯一的。当我们在核心数据中插入一个新的学生实体时,我已经验证了它。现在我在尝试更新现有学生数据时遇到问题,它总是返回相同的要更新的对象。我有学生的NSManagedbject,我希望它在我的获取请求中排除。

这是我的代码:

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

使用上面的代码,我在更新现有学生时总是得到1条记录

1 个答案:

答案 0 :(得分:0)

我是通过使用NSPredicate完成的,如下所示:

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
}