Sould I keep NSManagedObjectModel in a property for later use?

134 views Asked by At

Since I embeded fetch request in my model.xcdatamodeld, I need an instance of NSManagedObjectModel to get the fetch request from it. So I can do :

NSManagedObjectModel *managedObjectModel = [NSManagedObjectModel mergedModelFromBundles:nil];
NSFetchRequest *fetchRequest = [managedObjectModel fetchRequestFromTemplateWithName:requestTemplateName
                  substitutionVariables:substitutionDictionary];

My question is about the managedObjectModel. Should I keep it in a property to reuse ? or should I call mergedModelFromBundles when needed ?

I don't know the cost of a call of '[NSManagedObjectModel mergedModelFromBundles:nil]' in terms of memory/rapidity. The the name "mergeModelFrom" make me think that this hide some operations that could lead to bad bad performance if executed for each request in my application. Is that correct ?

1

There are 1 answers

0
Paul.s On BEST ANSWER

The Apple templates do this

- (NSManagedObjectModel *)managedObjectModel
{
    if (__managedObjectModel != nil) {
        return __managedObjectModel;
    }
    NSURL *modelURL = [[NSBundle mainBundle] URLForResource:@"DiscussIt" withExtension:@"momd"];
    __managedObjectModel = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelURL];
    return __managedObjectModel;
}

This way the creation is only done if managedObjectModel == nil, which is what you want.

Notice this is written in the getter so you don't need to worry about remembering to instantiate managedObjectModel as this is taken care of and lazily instantiated when you actually try to access it.