gpt4 book ai didi

Swift 2.0 核心数据 TableView 删除单元格

转载 作者:行者123 更新时间:2023-11-28 08:56:16 25 4
gpt4 key购买 nike

我们成功地实现了从 Core Data 中保存和读取,但是当删除随机单元格时,我们在从 Core Data 中删除数据时遇到了问题。从 tableView 中删除随机单元格时如何从 Core Data 中删除数据???我们输入了一些代码,例如从数组中删除最后一个索引,但它不起作用...

2cd VC

    import UIKit
import CoreData

class TableViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

@IBOutlet weak var tableView: UITableView!

var item = [NSManagedObject] ()

override func viewDidLoad() {
super.viewDidLoad()

self.tableView.delegate = self
self.tableView.dataSource = self
}

func tableView(tableView:UITableView, numberOfRowsInSection section:Int) -> Int
{
return item.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{

let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
let person = item[indexPath.row]
cell.textLabel!.text = person.valueForKey("username") as? String
cell.detailTextLabel?.text = person.valueForKey("passwords") as? String

return cell
}

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {


// WHAT TO TYPE HERE TO REMOVE DATA FROM CORE DATA WHEN RANDOM CELL IS DELETED
let context: NSManagedObjectContext = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext

do {
try context.save()
} catch _ {
}
}

override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)

let appDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let managedContext = appDelegate.managedObjectContext
let fetchRequest = NSFetchRequest(entityName: "Users")

do {
let results =
try managedContext.executeFetchRequest(fetchRequest)
item = results as! [NSManagedObject]
} catch let error as NSError {
print("Could not fetch \(error), \(error.userInfo)")
}
}

最佳答案

我发现它是这样工作的

func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {

switch editingStyle {
case .Delete:
// remove the deleted item from the model
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext
context.deleteObject(item[indexPath.row] as NSManagedObject)
item.removeAtIndex(indexPath.row)
do{
try context.save()
}catch{
print("Error, data not saved!")
}

//tableView.reloadData()
// remove the deleted item from the `UITableView`
self.tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
default:
return

}

关于Swift 2.0 核心数据 TableView 删除单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32951573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com