如何快速删除coredata数据库中的特定行数据
Posted
技术标签:
【中文标题】如何快速删除coredata数据库中的特定行数据【英文标题】:how to delete a particular row data in coredata database in swift 【发布时间】:2016-08-29 11:02:22 【问题描述】:请帮帮我
这是我的代码
//
import UIKit
import CoreData
class SavedPageViewController: UIViewController, UITableViewDataSource, UITableViewDelegate , NSFetchedResultsControllerDelegate
@IBOutlet weak var tableView: UITableView!
var tableTitleArray = [String]()
var tableDetailArray = [String]()
var tableTypeArray = [String]()
var tableHoursArray = [String]()
var tableImageArray = [NSData]()
override func viewDidLoad()
super.viewDidLoad()
// Do any additional setup after loading the view.
override func viewWillAppear(animated: Bool)
// core data - show
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
var request = NSFetchRequest(entityName: "SavedIdea")
request.returnsObjectsAsFaults = false;
do
var result:NSArray = try context.executeFetchRequest(request)
if (result.count > 0)
self.tableTitleArray = result.valueForKey("heading") as! [String]
self.tableDetailArray = result.valueForKey("detail") as! [String]
self.tableTypeArray = result.valueForKey("type") as! [String]
self.tableHoursArray = result.valueForKey("time") as! [String]
self.tableImageArray = result.valueForKey("image") as! [NSData]
else
print("0 result appear....error")
tableView.reloadData()
catch
let fetchError = ("returned error is \(error as! NSError)")
print(fetchError)
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
return self.tableTitleArray.count
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
let cell = tableView.dequeueReusableCellWithIdentifier("Cell")! as! OTPTableViewCell
cell.LabelTitle.text = tableTitleArray[indexPath.row]
cell.LabelDetail.text = tableDetailArray[indexPath.row]
cell.LabelType.text = tableTypeArray[indexPath.row]
cell.LabelHours.text = String(tableHoursArray[indexPath.row])+"h"
if tableImageArray[indexPath.row].length > 0
cell.ImgView.image = UIImage(data: tableImageArray[indexPath.row])
else
cell.imageWidthConstraints.constant = 0
return cell
func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath)
if editingStyle == .Delete
let appDel:AppDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
let context:NSManagedObjectContext = appDel.managedObjectContext
/* let deleterequest = NSFetchRequest(entityName: "SavedIdea")
deleterequest.returnsObjectsAsFaults = false
do
let savedData = try context.executeFetchRequest(deleterequest)
if savedData.count > 0
for result: AnyObject in savedData
context.deleteObject(result.valueForKey("heading"))
print("NSManagedObject has been Deleted")
try context.save() catch
我想从 tableview 中删除一个完整的行,即标题、详细信息、类型等。我的实体名称是 SavedData。我尝试了一些教程,但它们并没有满足我的需求。当我们向右滑动然后删除出现但不工作,因为我不知道代码。
【问题讨论】:
您正在删除实体本身而不是特定行,获取该特定行并执行删除操作并重新加载 tableview 查看***.com/questions/26047013/… 如果它解决了您的问题,请标记为正确答案 使用你奇怪的代码,这样做非常复杂(而且效率低下)。首先,您必须搜索并获取NSManagedObject
,因为您丢弃了引用,然后您必须删除代表数据源的 all 数组中行索引处的项目,然后您必须删除 @ Core Data 中的 987654324@,最后在 tableView 中调用 deleteRowsAtIndexPaths
。
【参考方案1】:
通过这种方式,您可以根据实体从 coredata 中删除数据:这是从 coredata 中删除用户实体数据的简单函数:希望对您有所帮助 //从核心数据中删除信息
func deleteUserInfo()
let context = appdelegate.managedObjectContext
let coord = appdelegate.persistentStoreCoordinator
let fetchRequest = NSFetchRequest(entityName: "entityname")
//Here is the field on which u need to chk which record u want to delete just pass here in value ( acutal value) unique key = field in coredata
let predicate = NSPredicate(format: "uniqueKey == %@", "value")
fetchRequest.predicate = predicate
if #available(ios 9.0, *)
//You can put condition to delete data accordingly
let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest)
do
try coord.executeRequest(deleteRequest, withContext: context)
catch let error as NSError
//Error handling
catch
else
// Fallback on earlier versions
do
let users: NSArray = try appdelegate.managedObjectContext.executeFetchRequest(fetchRequest)
//You can put condition to delete data accordingly
for user in users
appdelegate.managedObjectContext.delete(user)
try appdelegate.managedObjectContext.save()
catch let error as NSError
//Error handling
catch
【讨论】:
我想从表视图中删除选定的行,所以我把这段代码放在 - func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) ...... ........当我像这样将 indexpath.row 放在用户上时,它在这一行显示错误 ..appDel.managedObjectContext.delete(user(indexPath.row)) chck 参数 u 传递整数? 我正在使用此代码在视图控制器中显示我的数据 - chck 更新了答案,相应地更改了代码,在 coredata 中你需要使用 Predicate 来获取结果,然后你可以根据你的要求删除只是传递值和字段【参考方案2】:我希望这对于使用核心数据中的索引位置删除特定行很有用
func tableView(_ tableView: UITableView, commit editingStyle:
UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath)
let appDelegate = UIApplication.shared.delegate as! AppDelegate
let context = appDelegate.persistentContainer.viewContext
let requestDel = NSFetchRequest<NSFetchRequestResult>(entityName: "Contacts")
requestDel.returnsObjectsAsFaults = false
do
let arrUsrObj = try context.fetch(requestDel)
let objectUpdate = arrUsrObj as! [NSManagedObject]
context.delete(objectUpdate[indexPath.row]) // Deleting Object
catch
print("Failed")
// Saving the Delete operation
do
try context.save()
print("deleted")
fetch()
catch
print("Failed saving")
【讨论】:
以上是关于如何快速删除coredata数据库中的特定行数据的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Swift 从 CoreData sqlite 表中获取特定的行数据