Check registeredObjects before excuteFetchRequest:Error:
Not too sure if this is the right way of doing this, or if anyone has even tried, but be sure to check the registeredObjects NSArray of the NSManagedContext prior to fetching stuff. This of course only applies to SQLite backed stores, and this is done to reduce SQLite queries and inevitably disk I/O.
You can effectively query the registeredObjects using almost the same predicate as your subclassed NSManagedObjects in order to ensure that the NSManagedObject you want is the same.
Here’s some code to describe what I’m talking about.
+(ManagedLocation *)locationWithCoord:(CLLocationCoordinate2D)coord managedContext:(NSManagedObjectContext *)moc { // loop through registered objects for the type // you want and if they match your criteria // blocks rock! NSSet *result = [[moc registeredObjects] objectsPassingTest:^BOOL(id obj, BOOL *stop) { if ([obj isKindOfClass:[ManagedLocation class]]) { if ((((ManagedLocation *)obj).latValue == coord.latitude) && (((ManagedLocation *)obj).lngValue == coord.longitude)) { return YES; } } return NO; }]; // so if it doesn't exist. i guess we will have // to fetch off the sqlite store if ([result count] == 0) { result = [moc fetchObjectsForEntityName:[ManagedLocation entityName] withPredicate:@"(lat == %lf) && (lng == %lf)", coord.latitude, coord.longitude]; } // final check for existence. // // if it doesn't exist, create a new ManagedObject // and return it for population of values. if ([result count] == 1) { return [result anyObject]; } else { NSEntityDescription *locEntity = [NSEntityDescription entityForName:[ManagedLocation entityName] inManagedObjectContext:moc]; ManagedLocation *loc = [[[ManagedLocation alloc] initWithEntity:locEntity insertIntoManagedObjectContext:moc] autorelease]; loc.latValue = coord.latitude; loc.lngValue = coord.longitude; return loc; } }
So yeah. I was able to reduce by an order of magnitude, the time spent creating stuff.













