OWolf
OWolf

Reputation: 5132

Understanding NSURL, in the context of retrieving a persistent store document

Learning to use coreData. Currently looking at Stanford's CS193P Lecture 14, which is very helpful. I have successfully set up a working app with core data persistence, using a ManagedDocument.

This code below is run every time the app starts. My confusion is: how do we know that the url for the document is correct? How does it know that "lastObject" will always be the URL for the saved document?

if (!myManagedDocument) {        
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
    url = [url URLByAppendingPathComponent:@"theDatabase"];
    myManagedDocument = [[UIManagedDocument alloc]initWithFileURL:url];
}

This code below will open the document, or create/save it if it has not already been saved previously.

if (![[NSFileManager defaultManager] fileExistsAtPath:[myManagedDocument.fileURL path]]) {
        [myManagedDocument saveToURL:myManagedDocument.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL sucess) {
            [self getInfoFromDatabase];
        }];
    } else if (myManagedDocument.documentState == UIDocumentStateClosed) {
        [myManagedDocument openWithCompletionHandler:^(BOOL sucess) {
            [self getInfoFromDatabase];
        }];
    } else if (myManagedDocument.documentState == UIDocumentStateNormal) {
        [self getInfoFromDatabase];
    }

Upvotes: 1

Views: 125

Answers (1)

Martin R
Martin R

Reputation: 539925

Depending on the directory and domainMask argument, URLsForDirectory can return an array of several URLs. For example, on OS X,

NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSApplicationSupportDirectory inDomains:NSAllDomainsMask];

returns

(
file://localhost/Users/<user>/Library/Application%20Support/,
file://localhost/Library/Application%20Support/,
file://localhost/Network/Library/Application%20Support/
)

But in your case, on iOS,

NSArray *urls = [[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask];

returns an array of exactly one URL, which is the document directory inside the application sandbox. On the simulator, this would look like

(
file://localhost/Users/<user>/Library/Application%20Support/iPhone%20Simulator/5.0/Applications/AAAAAAAA-BBBB-CCCC-DDDD-EEEEEEEEEEEE/Documents/
)

So it does not matter if you take the first or last object of that array. The code just assumes that the managed document is saved in the document directory of the application sandbox.

Upvotes: 2

Related Questions