2

I have an app, using Core Data with a SQLite store.

At some point I'd like to remove all objects for a few entities. There may be close to a thousand objects.

From what I can tell via google and the official docs, the only way to delete objects is to [managedObjectContext deleteObject:(Entity *)] for every object. But this means that I must first fetch all objects.

The data store is just sqlite, is there no way to simply pass a TRUNCATE TABLE ZENTITY; to it?

thierryb
  • 3,660
  • 4
  • 42
  • 58
Prody
  • 5,182
  • 6
  • 44
  • 62

3 Answers3

9

If you relate your objects to a parent entity simply delete the parent. If your parents delete rule is set to 'cascade' all of those (1k) children will be removed as well.

John

John Bond
  • 176
  • 1
  • 6
  • 2
    I just came across this and intend to use this approach, but note that the cascade rule applies to entity relationships. Parent/child status is used for creating entity subtypes. – T. Markle Apr 20 '11 at 15:23
4

The issue is that CoreData isn't just a SQLite wrapper. It's an object graph management solution and it stores cached versions of your object in memory in addition to other stuff. As far as I know to remove all instances of a given managed object you'll have to fetch them and then delete each. This isn't to say that this functionality shouldn't exist, because it probably should.

Ben Lachman
  • 3,083
  • 1
  • 28
  • 44
0

Have you actually tried it and found it to be a performance issue? If so, then you could provide some information showing that, and more importantly file a bug report on it. If not, then why are you bothering to ask?

It's not as simple as doing a TRUNCATE TABLE ZENTITY; since Core Data must also apply the delete rule for each object (among other actions), which means doing a fetch. So they may as well let you make the fetch and then pass the results into the context one-by-one.

Mike Abdullah
  • 14,933
  • 2
  • 50
  • 75
  • I'm asking because I find it bad to fetch ~1k rows from a database when all you want to do is delete them. I haven't done a benchmark for it tho, but even if Core Data does lazy loading on all the objects, I'd still like to be able to do a truncate on the table since this doesn't even require counting first. – Prody Oct 16 '09 at 13:22
  • Doing things cumbersome way is always a bad solution, it doesn't matter if there is a performance issue related. – Michał Kreft Feb 28 '12 at 12:17
  • 1
    This isn't especially cumbersome though. It keeps the Core Data API lean, and makes it very clear what your code is doing. **Yes** if there's a performance problem, that's bad, but you need to measure that first. – Mike Abdullah Mar 03 '12 at 16:08