我将项目保存到收藏夹并在tableView中检索它们。但是现在用户可以添加这些项目的副本。我试图通过检查CoreData中是否已存在该项目来避免这种情况,从而防止该项目再次被保存。我怎样才能实现这个目标
var item: ItemModel?
func saveItemsToCoreDataStack(completion: @escaping ()-> Void) {
managedObjectContext!.perform {
do {
try self.managedObjectContext?.save()
completion()
print("Item saved to Database")
} catch {
print("Sorry Coudn't save itemto Database \(error.localizedDescription)")
}
}
}
var items = [Item]()
var managedObjectContext: NSManagedObjectContext? {
return (UIApplication.shared.delegate as! AppDelegate ).persistentContainer.viewContext
}
var fetchResultController: NSFetchedResultsController<Item>!
func retrieveitemsFromDatabase() {
fetchItemFromCoreData { (items) in
if let item = items {
self.items = item
self.tableView.reloadData()
}
}
}
func fetchItemFromCoreData(completion: ([Item]?)-> Void) {
var results = [Item]()
let request: NSFetchRequest<Item> = Item.fetchRequest()
do {
results = try managedObjectContext!.fetch(request)
completion(results)
} catch {
print("Sorry couldn't fetch item from Database \(error.localizedDescription)")
}
}
答案 0 :(得分:1)
以下是一种解决方案,您可以通过该解决方案阻止重复记录进入核心数据。
Swift 4.0
let entityForTableName = NSEntityDescription.entity(forEntityName: "EntityName", in: managedObjectContext)
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
// Predicate with value which are you wan't to be repeated i.e server_id, item_id etc.
let predicate = NSPredicate.init(format: "yourUniqueKey == %@", <YourUniqueValue>)
fetchRequest.predicate = predicate
fetchRequest.entity = entityForTableName
do {
let arrData = try managedObjectContext.fetch(fetchRequest)
if arrData.count > 0 {
print("Record already exist")
} else {
// Write your code here to add record
}
} catch {
print(error.localizedDescription)
}
目标C
// Solution for objective c also
NSEntityDescription *yourEntityObject = [NSEntityDescription entityForName:@"YourEntityName" inManagedObjectContext:_managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"uniqueField == %d", <ValueToCheckAlreadyExist>];
[fetchRequest setEntity:yourEntityObject];
NSArray *arrData = [_managedObjectContext executeFetchRequest:fetchRequest error:nil];
if ([arrData count] > 0) {
// Data already exist
} else {
// Create new data
}