KML
KML

Reputation: 2322

Core Data: How do I delete all objects with an attribute in Swift?

Say for simplicity that I have an entity named DOWJONES. There are two attributes for every object ex AAPL and AAPL_NSDate. ValueForKey:AAPL returns the stock price history and ValueforKey AAPL_NSDate the corresponding date.

How can I delete the stockprice history and corresponding date quickly and efficiently in swift?
This is how I query:

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

    var request = NSFetchRequest(entityName: "DOWJONES")
    request.returnsObjectsAsFaults = false
    var dowjones = context.executeFetchRequest(request, error: nil)! as [DOWJONES]
    var aapl = (dowjones as NSArray).valueForKey("AAPL") as NSArray

As suggested from @chris-wagner this is how I could iterate over the results and delete.

func deleteCoreDataObjects(){
    var request = NSFetchRequest(entityName: "DOWJONES")
    request.returnsObjectsAsFaults = false
    var dowjones = context.executeFetchRequest(request, error: nil)!

    if dowjones.count > 0 {

        for result: AnyObject in dowjones{
            context.deleteObject(result as NSManagedObject)
            println("NSManagedObject has been Deleted")
        }
        context.save(nil)
    }
}

Upvotes: 1

Views: 1282

Answers (2)

jrturton
jrturton

Reputation: 119242

You can do batch requests directly onto the data store as of iOS 8, using NSPersistentStoreCoordinator's executeRequest(_ request: NSPersistentStoreRequest, withContext context: NSManagedObjectContext, error error: NSErrorPointer) method.

You create the persistent store request similarly to a fetch request, then pass it to the PSC using the above method.

Note however that you shouldn't have any in-context references to objects you're deleting with this method.

There's a nice explanation of it here.

Upvotes: 3

Chris Wagner
Chris Wagner

Reputation: 21003

Iterate over the results from your fetch request and call self.context.deleteObject(_:) on each one.

Upvotes: 2

Related Questions