I am learning iOS via Standford CS193P, I met a problem in core data part.
I am trying to build an app using core data, I create a category for the AppDelegate(I will create a UIManagedDocument in didFinishLaunchingWithOptions), this category implement one method to create a UIManagedDocument and return it to the AppDelegate, so that I can call self.managedDocument = [self createUIManagedDocument] to get one:
- (UIManagedDocument *)createUIManagedDocument
{
NSFileManager *fileManager = [NSFileManager defaultManager];
NSURL *documentsDirectory = [[fileManager URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] firstObject];
NSURL *url = [documentsDirectory URLByAppendingPathComponent:APP_NAME];
UIManagedDocument *managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
// If the file exists, open it
NSLog(@"File exists, not opening...");
[managedDocument openWithCompletionHandler:^(BOOL success) {
NSLog(@"File opened.");
}];
} else {
// If the file not exists, create it
NSLog(@"File not exists, now creating...");
[managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
// If the file create succesfully, open it
[managedDocument openWithCompletionHandler:^(BOOL success) {
NSLog(@"File opened.");
}];
}];
}
return managedDocument;
}
After the UIManagedDocument creation, I am trying to pass this UIManagedDocument to my view controllers using:
RootViewController *rootViewController = (RootViewController *)self.window.rootViewController;
rootViewController.managedDocument = self.managedDocument;
And the problem occurs, I am unable to open the UIManagedDocument in my view controllers. I searched it for a whole day and got the answer: I was trying to open it twice at the same time while it is asynchronous, it takes time to process the IO request. There are some approaches, and most of them using Singleton.
Here is my question:
- Can I do this by using the approach above?
- If no, what is the standard(or correct) way to create and pass this UIManagedDocument around my app?
- Should I pass NSManagedObjectContext in this UIManagedDocument to my view controllers instead of passing UIManagedDocument?
Thank you for reviewing my question.