salfasano
salfasano

Reputation: 297

Memory increasing every core data iteration

Having a memory issue while iterating through my core data objects. As it loops through CFData (store) keeps increasing until the application crashes. Shouldn't core data release the memory after every loop finishes?

for (Patient *patient in self.fetchedResultsController.fetchedObjects) {
    for (Exam *examForPatient in patient.exams) {
        //do stuff with examForPatient
    }
}

Edit - Tried the following and still behaving the same way:

for (Patient *patient in self.fetchedResultsController.fetchedObjects) {
    for (Exam *examForPatient in patient.exams) {
        NSLog(@"%@", [examForPatient.examDate description]);

        [self.fetchedResultsController.managedObjectContext refreshObject:examForPatient mergeChanges:NO];
    }
    [self.fetchedResultsController.managedObjectContext refreshObject:patient mergeChanges:NO];
}

Upvotes: 3

Views: 530

Answers (2)

lnafziger
lnafziger

Reputation: 25740

Whenever you access a managed object, it fires the fault and loads the full object from the store. It doesn't release the memory until you specifically tell it to. Change your code to:

for (Patient *patient in self.fetchedResultsController.fetchedObjects) {
    for (Exam *examForPatient in patient.exams) {
        //do stuff with examForPatient

        // Then release the memory.  As below, save first if needed.
        [yourManagedObjectContext refreshObject:examForPatient mergeChanges:NO];
    }

    // Then release the memory - save patient first if you have made changes to it.
    [yourManagedObjectContext refreshObject:patient mergeChanges:NO];
}

Upvotes: 0

Dan Shelly
Dan Shelly

Reputation: 6011

When you no longer have need for an item to reside in memory, you can refresh it.
from the docs:
"If you iterate over a lot of objects, you may need to use local autorelease pool blocks to ensure temporary objects are deallocated as soon as possible"

Edit: see @lnafziger answer

Note: if you are updating your patient object or exam objects, you cannot refresh it as you will loose all changes to it (if you use mergeChanges:YES you will not release its memory). you will then need to save periodically and refresh the objects you no longer need.

See here for more information.

Upvotes: 1

Related Questions