I have a helper class that distributes a shared instance of UIManagedDocument. The idea is that the user requests the UIManagedDocument shared instance for a particular file on disk. In this case, it's a core data store. If the user requests the core data store located at a different path I want to distribute an instance of UIManagedDocument for that file.
My question is: Is it ok to create a new instance of a UIManagedDocument and assign it to the static variable when the file changes? For example:
+ (UIManagedDocument *)sharedManagedDocumentForFile:(NSString *)fileName
{
static UIManagedDocument *sharedDocument = nil;
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:fileName];
// url is "<Documents Directory>/<vacationName>"
// Create the shared instance lazily upon the first request.
if (sharedDocument == nil) {
sharedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
}
if (sharedDocument.fileURL != url) {
UIManagedDocument *newDocument = [[UIManagedDocument alloc] initWithFileURL:url];
sharedDocument = newDocument;
}
return sharedDocument;
}
Basically what I'm trying to do is distribute only one instance of a UIManagedDocument so in the event there are multiple writers to the core data store I don't have to constantly keep the changes in sync. However, since there are multiple core data stores on disk I can't just distribute the same static variable every time.
Any ideas? I'm absolutely stuck on even how to approach this design problem... Any help is appreciated.
Thanks - Jake