如何使用滑动删除实体以删除iOS tableview

时间:2017-03-18 07:47:54

标签: ios swift xcode uitableview core-data

我一直在努力让我的预算应用与coreData一起正常运作。到目前为止,该应用程序能够保存用户输入的数据,tableview可以成功加载数据并正确显示。

问题是当用户在桌面上滑动删除时,我无法弄清楚如何删除一个项目。我认为我的整个coreData模型都是错的,但我不确定如何修复它或正确设置它!

这是我在ViewController中的代码

 /***************************************
* numberOfRowsInSection:
*  This function gets a count of all the
* objects that are stored in the MoneyEntity
* table.
****************************************/
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

  return CoreDataManager.fetchObjects().count

}

/***************************************
* cellForRowAt indexPath:
*  This function populates all the cells
* with the data from the MoneyEntity
* objects.
****************************************/
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {


  let cell = self.budgetTable.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! cellLog

  //alternates between colors
  if (indexPath.row % 2 ) != 0
  {
     cell.contentView.backgroundColor = UIColor.init(red: 1, green: 1, blue: 1, alpha: 0.5)
  }
  else
  {
     cell.contentView.backgroundColor = UIColor.white
  }

  // load data into cell

  cell.moneyLabel.text = "$\(String(format:"%.2f", CoreDataManager.fetchObjects()[indexPath.row].money))"
  cell.dateLabel.text = "\(CoreDataManager.fetchObjects()[indexPath.row].date)"
  cell.noteImage.image = UIImage(named: "notes")

  return cell

}

/***************************************
* editingStyle:
*  This function lets the user "swipe to delete"
* in the tableView
****************************************/
func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath)
{
  if editingStyle == UITableViewCellEditingStyle.delete
  {

     // **** what do I do here?????

     //why wont this work?!
     let context = CoreDataManager.getContext()
     context.deleteObject(CoreDataManager.fetchObjects()[indexPath.row] as NSManagedObject)
     context.save(nil)


   //print(CoreDataManager.fetchObjects()[indexPath.row])

   //         var index = Int(indexPath.row)
   //         CoreDataManager.deleteSing

     // remove the deleted item from the `UITableView`
     self.budgetTable.deleteRows(at: [indexPath], with: .fade)


    //         budgetTable.reloadData()
  }
}

好的,这是我的CoreDataManager类的代码

class CoreDataManager: NSObject
{
/***************************************
* getContext:
*  This function sets us up with the abillity
* to start using coredata functions
****************************************/
public class func getContext() -> NSManagedObjectContext
{
  let appDelegate = UIApplication.shared.delegate as! AppDelegate
  return appDelegate.persistentContainer.viewContext
}

/***************************************
* storeObject:
*  This function saves the data to a 
* MoneyEntity object
****************************************/
class func storeObject(destination:String, money:Double, date:String, note:String)
{
  let context = getContext()

  let entity = NSEntityDescription.entity(forEntityName: "MoneyEntity", in: context)

  let managedObj = NSManagedObject(entity: entity!, insertInto: context)

  //save data
  managedObj.setValue(money, forKey: "money")
  managedObj.setValue(date, forKey: "date")
  managedObj.setValue(note, forKey: "note")

  do
  {
     try context.save()
     print("Data save successful")
  }
  catch
  {
     print("Failed to save data")
     print(error.localizedDescription)

  }
 }

 /***************************************
* fetchObjects:
*  This function loads all the MoneyEntity
* objects into an array that gets returned
* to numberOfRowsInSection so that it can
* see how many MoneyEntity objects there are
* so that it can create the right about of
* cells.
****************************************/
class func fetchObjects() -> [moneyLog]
{
  var tempArray = [moneyLog]()

  let fetchRequest:NSFetchRequest<MoneyEntity> = MoneyEntity.fetchRequest()

  do {
     let fetchResult = try getContext().fetch(fetchRequest)

     for item in fetchResult
     {
        let newMoneyLog = moneyLog(money: item.money, date: item.date!, note: item.note!)
        tempArray.append(newMoneyLog)
     }

  }
  catch {
     print("fetch faild")
  }

  return tempArray
}


/***************************************
* cleanCoreData:
*  This function clears all data from
* coreData.
****************************************/
class func cleanCoreData()
{
  let fetchRequest:NSFetchRequest<MoneyEntity> = MoneyEntity.fetchRequest()

  let deleteRequest = NSBatchDeleteRequest(fetchRequest: fetchRequest as! NSFetchRequest<NSFetchRequestResult>)

  do {
     print("deleting all content")
     try getContext().execute(deleteRequest)
  } catch {
     print("There was a problem deleting all items")
  }

}

MoneyEntity数据模型

enter image description here

0 个答案:

没有答案