核心数据:在 swift 中的获取请求中排除 NSManagedObject
Core Data: Exclude a NSManagedObject in fetch request in swift
我有一个名为 "Student" 的实体,用于存储学生的数据。学生的手机号码必须是唯一的。当我们在核心数据中插入一个新的学生实体时,我已经验证了它。现在,当我尝试更新现有学生数据时遇到问题,它总是 returns 要更新的同一对象。我有一个学生的 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 条记录
我已经通过使用如下所示的 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
}
我有一个名为 "Student" 的实体,用于存储学生的数据。学生的手机号码必须是唯一的。当我们在核心数据中插入一个新的学生实体时,我已经验证了它。现在,当我尝试更新现有学生数据时遇到问题,它总是 returns 要更新的同一对象。我有一个学生的 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 条记录
我已经通过使用如下所示的 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
}