简体   繁体   中英

how to delete row from coredata (Entity) ios swift

i am new to CORE DATA in my app i am using coredata. i just stored data in my core data. my entity name is "FEED" and i have a rows with name "title", "id " , "link" ,"desc" so now i want to delete perticular row on based on "id". so how can i do this?

Here is my code,

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell : MessageMusicCell = tableView.dequeueReusableCellWithIdentifier("MessageMusicCell") as! MessageMusicCell

    cell.pinButton.tag = indexPath.row
    cell.pinButton.addTarget(self, action: #selector(MessageViewController.buttonDeletePressed(_:)), forControlEvents: UIControlEvents.TouchUpInside)
    cell.selectionStyle = .None



        person = people[indexPath.row]
        cell.lbl_title_msg_music.text = person!.valueForKey("title") as? String
        cell.img_message_music.image = UIImage(named: "PlaceHolder")
        cell.desc_msg_music.text = person!.valueForKey("desc") as? String


    return cell
}

func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

        print(people.count)
        return people.count


}

func buttonDeletePressed(sender:UIButton) {


}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {

    let cell : MessageMusicCell = tableView.dequeueReusableCellWithIdentifier("MessageMusicCell") as! MessageMusicCell


}

so how can i do this?

Try Like this,

func buttonDeletePressed(sender:UIButton) {

        let appDel:AppDelegate = UIApplication.sharedApplication().delegate as! AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext

        let index = sender.tag

        context.deleteObject(people[index] as NSManagedObject)
        people.removeAtIndex(index)

        let _ : NSError! = nil
        do {
            try context.save()
            self.tableView.reloadData()
        } catch {
            print("error : \(error)")
        }
}

Hope this will help you.

func deleteFeed(id:String)
{
    let appDelegate =
        UIApplication.sharedApplication().delegate as? AppDelegate
    let managedContext = appDelegate?.managedObjectContext
    let fetchRequest = NSFetchRequest(entityName:"FEED")
    fetchRequest.predicate = NSPredicate(format: "id = %@", "\(id)")
    do
    {
        let fetchedResults =  try managedContext!.executeFetchRequest(fetchRequest) as? [NSManagedObject]

        for entity in fetchedResults! {

            managedContext?.deleteObject(entity)
        }
    }
    catch _ {
        print("Could not delete")

    }
}

Now you can call this function and pass the id whatever you want to delete

func buttonDeletePressed(sender:UIButton){
   deleteFeed("1")
}

You can delete data like,

  let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
        let context:NSManagedObjectContext = appDel.managedObjectContext!
        context.deleteObject(myData[indexPath.row] as NSManagedObject)
        myData.removeAtIndex(indexPath.row)
        context.save(nil)

this is done from commitEditingStyle so here used indexPath.row . You can pass your id if you want to delete data from other place. If you want to delete data from tableview then you should implement commitEditingStyle and delete data like mentioned above.

Hope this will help :)

override 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(people[indexPath.row] )
    people.removeAtIndex(indexPath.row)
    do {
        try context.save()
    } catch _ {
    }

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

Hope this could be of some help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM