5
votes

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;
}
1
your singleton method looks like the way to go. you could move the url creation code inside dispatch_once to optimize it.Felix
Great, thank you, to give credit where credit is due: Colin Wheeler was my inspiration - stackoverflow.com/a/2200751/1096476uem

1 Answers

0
votes

If you have existing UIManagedDocuments on disk, you need to search the directory for matching files. Typically, the files would have some identifying attribute, like a common file extension.

Something like this:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSURL *appDirectoryURL = [appDelegate applicationDocumentsDirectory];
NSArray *directoryContents = [[NSFileManager defaultManager] contentsOfDirectoryAtURL:appDirectoryURL includingPropertiesForKeys:nil options:NSDirectoryEnumerationSkipsHiddenFiles error:nil];

for (NSURL *fileURL in directoryContents) {
    NSString *documentExtension = [fileURL pathExtension];

    if ([documentExtension isEqualToString:@"myfileextension"]) {
    }
}