func deleteData(id:String){
let fetchRequest = NSFetchRequest<NSManagedObject>(entityName: "User")
fetchRequest.predicate = NSPredicate(format: "id = '\(id)'")
do
{
let test = try context.fetch(fetchRequest)
let objectToDelete = test[0]
context.delete(objectToDelete)
do{
try context.save()
}
catch(let error)
{
print(error.localizedDescription)
}
}
catch(let error)
{
print(error)
}
}
This is delete function
class SecondViewController: UIViewController,UITableViewDelegate,UITableViewDataSource {
var array = [Dictionary<String,String>]()
@IBOutlet weak var tableview: UITableView!
var id = ""
var obj = Dictionary<String,String>()
override func viewDidLoad() {
super.viewDidLoad()
self.tableview.delegate = self
self.tableview.dataSource = self
array = DataHandler.sharedInstance.fetch()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return array.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let obj = array[indexPath.row]
let cell = tableView.dequeueReusableCell(withIdentifier: "cell") as! TableViewCell
cell.usernameLabel.text = obj["username"]
cell.emailLabel.text = obj["email"]
cell.passwordLabel.text = obj["password"]
cell.updateBtn.addTarget(self, action: #selector(didTapUpdateBtn(sender:)), for: .touchUpInside)
cell.updateBtn.tag = indexPath.row
return cell
}
@objc func didTapUpdateBtn(sender:UIButton)
{
let obj = array[sender.tag]
let sb = UIStoryboard.init(name: "Main", bundle: nil)
let vc = sb.instantiateViewController(identifier: "update") as! UpdateViewController
vc.obj = obj
self.present(vc, animated: true, completion: nil)
}
This is tableview controller
class TableViewCell: UITableViewCell {
@IBOutlet weak var usernameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var passwordLabel: UILabel!
@IBOutlet weak var idLabel: UILabel!
@IBOutlet weak var updateBtn: UIButton!
@IBOutlet weak var deleteBtn: UIButton!
override func awakeFromNib() {
super.awakeFromNib()
// Initialization code
}
override func setSelected(_ selected: Bool, animated: Bool) {
super.setSelected(selected, animated: animated)
// Configure the view for the selected state
}
This is table view cell
I am performing crud operation with core data.I have performed 3 operation successful which is working fine but in delete operation we have no need to navigate another controller just click on button action will be performed.I am so confused how to do it i have tried so many method.
Use below code:
cell.deleteBtn.tag = obj["id"]
Where obj = array[indexPath.row]
So you will definitely get id for specific row to delete.
After deleting row also use code
self.tableView.deleteRows(at: [indexPath], with: .automatic)
.
This will remove row from tableview. OR Just reload your TableView by using below code.
self.dataDisplayTbleView.reloadData()