Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CoreData delete single object

I'd like to delete an entry in the entity Person at the attribute name which matches with the value Test.

For example I saved an entry into core data like this: object.setValue("Test", forKey: "markedCell"). Now I want to find out if the entry "Test" is saved in the attribute markedCell and which indexPath it has. I tried the following one:

var request:NSFetchRequest = NSFetchRequest(entityName: "Person") request.predicate = NSPredicate(format:"markedCell = %@", "Test") var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]

Now I know if the entry "Test" exists but don't know which indexPath it has (I can only delete an entry if I know which indexPath it has right?). Currently I want to delete the entry "Test" (don't wanna set it to "").

My CoreData model:

I want to delete <code>"Test"</code> from <code>markedCell</code>

I want to delete "Test" from markedCell.

Does someone of you guys know how to do this in Swift ?

Creating a cell (cellForRowAtIndexPath):

//Get task
    let context = self.fetchedResultsController.managedObjectContext
    let object = self.fetchedResultsController.objectAtIndexPath(indexPath) as NSManagedObject
    var taskString:NSString?
    taskString = object.valueForKey("name") as? String
    cell.textLabel!.text = object.valueForKey("name") as? String

    println(object.valueForKey("name") as? String)

    //Set accessory type
    var request:NSFetchRequest = NSFetchRequest(entityName: "Person")
    request.predicate = NSPredicate(format:"markedCell = %@", taskString!)
    var results : [NSManagedObject] = context.executeFetchRequest(request, error: nil) as [NSManagedObject]
    if (results.count > 0) {
        //Element exists
        cell.accessoryType = UITableViewCellAccessoryType.None
        println("Cell isn't marked")
    }
    else {
        //Doesn't exist
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        println("Cell is marked")
    }

Crash:

enter image description here

enter image description here

I hope this pic helps to understand my question better. The link of the image: https://www.dropbox.com/s/h5g4yeoedg0xjjv/Stackoverflow_Question.png?dl=0

like image 901
horst Avatar asked Mar 17 '23 04:03

horst


2 Answers

I can only delete an entry if I know which indexPath it has right?

This is wrong. A Core Data object does not have an index path. (A fetched results controller manages Core Data objects for display in a table view and then you have index paths, but that is completely irrelevant here.)

Just fetch the object or the objects that you want to delete and delete them:

let request = NSFetchRequest(entityName: "Person")
request.predicate = NSPredicate(format:"markedCell = %@", "Test")
if let results = context.executeFetchRequest(request, error: nil) as? [NSManagedObject] {

    // Delete _all_ objects:
    for object in results {
        context.deleteObject(object)
    }

    // Or delete first object:
    if results.count > 0 {
        context.deleteObject(results[0])
    }

} else {
    // ... fetch failed, report error
}
like image 56
Martin R Avatar answered Mar 22 '23 21:03

Martin R


For Swift 3:

       if let dataAppDelegatde = UIApplication.shared.delegate as? AppDelegate {


                let mngdCntxt = dataAppDelegatde.persistentContainer.viewContext

                let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "ItemCart")

                let predicate = NSPredicate(format: "itemId = %i", Int(currentItemID)!)
                print(currentItemID)

                fetchRequest.predicate = predicate
                do{
                    let result = try mngdCntxt.fetch(fetchRequest)

                    print(result.count)

                    if result.count > 0{
                        for object in result {
                            print(object)
                            mngdCntxt.delete(object as! NSManagedObject)
                        }
                    }
                }catch{

                }
            }
like image 40
Sandu Avatar answered Mar 22 '23 20:03

Sandu