1

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)
    }
}

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

TIL! So much to keep up on :)
2

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

2 Comments

Is there really no faster way, like delete all of them at once?
Nope, not that I've seen. You could write a convenience method if you're going to be doing this often ;)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.