I've already taken a look at How do I create a global UIManagedDocument instance per document-on-disk shared by my whole application using blocks? but I don't really get it.
What I want to achieve is that there should be only one UIManagedDocument - a core data database - for the whole app. Different Objects should be calling a method and get the one and only UIManagedDocument.
I use a helper class with a class method:
+ (UIManagedDocument *)getsharedDatabase:(NSString *)databaseName
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:databaseName];
// url is now "<Documents Directory>/<databaseName>"
if (![[NSFileManager defaultManager] fileExistsAtPath:[url absoluteString]])
{
// does not exist on disk, so create one
UIManagedDocument *managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
return managedDocument;
}
else
{
UIManagedDocument *managedDocument = **?????**
return managedDocument;
}
}
As you can see by the question marks, I don't know how to get the existing file. I checked the UIManagedDocument class reference but couldn't find it.
Can you help me, please? Many thanks in advance.
EDIT I was wondering ... what about a singleton method such as:
+ (UIManagedDocument *) sharedDatabase
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"databaseName"];
// url is now "<Documents Directory>/databaseName"
static UIManagedDocument *managedDocument = nil;
static dispatch_once_t mngddoc;
dispatch_once(&mngddoc, ^{
managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
});
return managedDocument;
}