I am using the following code to retrieve the maximum value of an attribute on Core Data
- (NSDate*)latestDateForLocalEntity:(NSString*)entityString
key:(NSString*)key
inManagedObjectContext:(NSManagedObjectContext*)context {
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityString];
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:key ascending:YES];
request.sortDescriptors = @[sortDescriptor];
NSError *localError;
NSArray *localResults = [context executeFetchRequest:request error:&localError];
id result = localResults.lastObject;
NSDate *latestLocalDate = [result valueForKey:key];
NSLog(@"Latest local date for entity %@ (%@): %@",entityString,key,latestLocalDate);
// fault newly created objects - don`t need to keep them in RAM:
[localResults enumerateObjectsUsingBlock:^(NSManagedObject *managedObject, NSUInteger idx, BOOL *stop) {
[context refreshObject:managedObject mergeChanges:NO];
}];
// even context reset does not help reducing RAM consumption:
[context reset];
localResults = nil;
return latestLocalDate;
The code retrieves all entities, sorts them by value and takes the last object to get the maximum value. It then tries to (re)fault the values in order to release RAM: [context refreshObject:managedObject mergeChanges:NO]
.
However, memory seems not being released (roughly 400.000 non-object
objects are kept in memory).
What is wrong with my code trying to refault the objects and resetting the managed object context? Why does it not release memory?