Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 7949477
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 4, 20262026-06-04T02:00:36+00:00 2026-06-04T02:00:36+00:00

The way I’m trying to delete multiple sets of 10.000+ NSManagedObjects is just too

  • 0

The way I’m trying to delete multiple sets of 10.000+ NSManagedObjects is just too memory intensive (around 20MB live bytes), and my app is being jettisoned. Here is the implementation of the delete method:

+ (void)deleteRelatedEntitiesInManagedObjectContext:(NSManagedObjectContext *)context 
{
    NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
    [context setUndoManager:nil];

    [fetch setEntity:[NSEntityDescription entityForName:NSStringFromClass(self) inManagedObjectContext:context]];
    [fetch setIncludesPropertyValues:NO];

    NSError *error = nil;
    NSArray *entities = [context executeFetchRequest:fetch error:&error];

    NSInteger deletedCount = 0;
    for (NSManagedObject *item in entities) {
        [context deleteObject:item];
        deletedCount++;

        if (deletedCount == 500) {
            [context save:&error];
            deletedCount = 0;
        }
    }

    if (deletedCount != 0) {
        [context save:&error];
    }
}

I’ve tried: -setFetchBatchSize, but there’s even more memory used.

What would be a more memory-efficient way to do this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-04T02:00:37+00:00Added an answer on June 4, 2026 at 2:00 am

    EDIT: Just watched 2015 WWDC “What’s New in Core Data” (it’s always the first video I watch, but I’ve been very busy this year) and they announced a new API: NSBatchDeleteRequest that should be much more efficient than any previous solution.


    Efficient has multiple meanings, and most often means some sort of trade-off. Here, I assume you just want to contain memory while deleting.

    Core Data has lots of performance options, beyond the scope of any single SO question.

    How memory is managed depends on the settings for your managedObjectContext and fetchRequest. Look at the docs to see all the options. In particular, though, you should keep these things in mind.

    Also, keep in mind the performance aspect. This type of operation should be performed on a separate thread.

    Also, note that the rest of your object graph will also come into play (because of how CoreData handles deletion of related objects.

    Regarding memory consumption, there are two properties on MOC in particular to pay attention to. While there is a lot here, it is by no means close to comprehensive. If you want to actually see what is happening, NSLog your MOC just before and after each save operation. In particular, log registeredObjects and deletedObjects.

    1. The MOC has a list of registered objects. By default, it does not retain registered objects. However, if retainsRegisteredObjects is YES, it will retain all registered objects.

    2. For deletes in particular, setPropagatesDeletesAtEndOfEvent tells the MOC how to handle related objects. If you want them handled with the save, you need to set that value to NO. Otherwise, it will wait until the current event is done

    3. If you have really large object sets, consider using fetchLimit. While faults do not take a lot of memory, they still take some, and many thousands at a time are not insignificant. It means more fetching, but you will limit the amount of memory

    4. Also consider, any time you have large internal loops, you should be using your own autorelease pool.

    5. If this MOC has a parent, saving only moves those changes to the parent. In this case, if you have a parent MOC, you are just making that one grow.

    For restricting memory, consider this (not necessarily best for your case — there are lots of Core Data options — only you know what is best for your situation, based on all the options you are using elsewhere.

    I wrote a category on NSManagedObjectContext that I use for saving when I want to make sure the save goes to the backing store, very similar to this. If you do not use a MOC hierarchy, you don’t need it, but… there is really no reason NOT to use a hierarchy (unless you are bound to old iOS).

    - (BOOL)cascadeSave:(NSError**)error {
        __block BOOL saveResult = YES;
        if ([self hasChanges]) {            
            saveResult = [self save:error];
        }
        if (saveResult && self.parentContext) {
            [self.parentContext performBlockAndWait:^{
                saveResult = [self.parentContext cascadeSave:error];
            }];
        }
        return saveResult;
    }
    

    I modified your code a little bit…

    + (void)deleteRelatedEntitiesInManagedObjectContext:(NSManagedObjectContext *)context 
    {
        NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
        [context setUndoManager:nil];
    
        [fetch setEntity:[NSEntityDescription entityForName:NSStringFromClass(self) inManagedObjectContext:context]];
        [fetch setIncludesPropertyValues:NO];
        [fetch setFetchLimit:500];
    
        NSError *error = nil;
        NSArray *entities = [context executeFetchRequest:fetch error:&error];
        while ([entities count] > 0) {
            @autoreleasepool {
                for (NSManagedObject *item in entities) {
                    [context deleteObject:item];
                }
                if (![context cascadeSave:&error]) {
                    // Handle error appropriately
                }
            }
            entities = [context executeFetchRequest:fetch error:&error];
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Fastest way to interface between live (unsaved) Excel data and C# objects features a
Way cool, i'd just realised there is something called flood-color and lighting-color in CSS.
The way I currently handle this is by having multiple config files such as:
Way back in the days when delicious was just del.icio.us, I had assumed that
The way I understand how Kue works, I need to specify the type of
The way I have my page set up right now is pretty solid. I
The way I understand it, when MySQL performs a LIKE query, depending on how
Any way of using the data_response outside the $.post() ? This is part of
Which way is the best to show message in Controller? Is must showing count
The way I understand it one of the things special about Objective C is

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.