[英]Swift 3: How to delete the single record in the Core Data when a UIbutton is Pressed
我有一个功能,我可以将配置文件添加到收藏夹列表(通过核心数据保存),当我想将其标记为“不喜欢”时,它应该从核心数据和表列表视图(收藏夹视图控制器)中删除)。
到目前为止,我拥有的代码从列表中删除所有记录,而不是删除特定记录。
请在下面找到代码:-
@IBAction func saveFav(_ sender: UIButton) {
let propertyToCheck = sender.currentTitle!
var proID = saved_id
let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
let task = FavProfile(context: context)
switch propertyToCheck {
case "Add to Favourite":
// Link Task & Context
task.busName = bussinessName
task.profileID = Int32(id!)!
print ("saved id is: - \(task.profileID)")
print ("saved profile name is: - \(task.busName)")
fav_remove_fav_button_label.setTitle("Remove From Favourite", for: .normal)
// Save the data to coredata
(UIApplication.shared.delegate as! AppDelegate).saveContext()
let _ = navigationController?.popViewController(animated: true)
let alert = UIAlertController(title: "Alert", message: "Added to your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
case "Remove from Favourite":
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
} catch {
}
let alert = UIAlertController(title: "Alert", message: "Removed from your Favourite list", preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
// self.favtable.tableView.reloadData()
default: break
}
}
我不知道我需要在这里修复什么,只删除特定的记录。
感谢您的时间和努力。
屏幕 1,当我将个人资料标记为收藏时:
当我将相同的个人资料标记为不喜欢时的屏幕 2:
屏幕 3,当我再次重新启动应用程序时:
我试图将第二个配置文件标记为不喜欢,它不会更新 tableview。 当我重新启动应用程序时,它显示“标签”
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "FavProfile")
let predicate = NSPredicate(format: "profileID == %@", id as CVarArg)
fetchRequest.predicate = predicate
let moc = getContext()
let result = try? moc.fetch(fetchRequest)
let resultData = result as! [FavProfile]
for object in resultData {
moc.delete(object)
}
do {
try moc.save()
print("saved!")
} catch let error as NSError {
print("Could not save \(error), \(error.userInfo)")
}
对 profileID 使用谓词。
let predicate = NSPredicate(format: "name == %@ AND type == %@", "your target name","your target type")
var fetchedEntities = [TrackTable]()
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "TrackTable")
fetchRequest.predicate = predicate
do {
fetchedEntities = try! managedContext?.fetch(fetchRequest) as! [TrackTable]
for sequence in fetchedEntities
{
managedContext?.delete(sequence)
}
catch
{
}
}
在上面的谓词name
和type
是您要删除特定实体的表实体。
* Add a Predicate Like given below to search for a particular item from the list of Favourites using it's unique profile Id. Search for that item in it's entity and delete that item from core data.
*****************************************
let predicateFavs = NSPredicate(format: “profileID = %@", String(describing: id!))
let favList = CoreDataHandler.sharedInstance.fetchEntityWithName(“FavProfile”, predicate: predicateFavs) as! [FavProfile]
context.performAndWait({
for object in favList{
self.context.delete(object)
}
do {
try self.context.save()
} catch {
print("error : \(error)")
}
})
********************************************
func fetchEntityWithName(_ entityName : NSString, predicate: NSPredicate) -> NSArray{
// Create Entity Description
let entityDescription = NSEntityDescription.entity(forEntityName: entityName as String, in: context)
// Initialize Fetch Request
let fetchRequest = NSFetchRequest<NSFetchRequestResult>()
// Configure Fetch Request
fetchRequest.entity = entityDescription
fetchRequest.predicate = predicate
var result = NSArray()
do {
result = try context.fetch(fetchRequest) as NSArray
print(result)
} catch {
let fetchError = error as NSError
print(fetchError)
}
return result
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.