I am using Core Data to store a few simple strings related to each user. When the app first starts, everything seems to be fine. The database opens, and I am successfully able to save and retrieve data.
However, after some usage, sometimes the UIManagedDocument
I use will just not open when the app starts. Here is the method I use for that (done in the app delegate):
-(void)initManagedDocument{
@try {
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"DataBase"];
self.managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]){
[self.managedDocument openWithCompletionHandler:^(BOOL success){
if (success) {
[self documentIsReady];
}else{
NSLog(@"Could not open document");
}
}];
}else{
[self.managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
if (success) {
[self documentIsReady];
}else{
NSLog(@"Could not create document");
}
}];
}
}
@catch (NSException *e) {
}
}
This code gets called from my app's didFinishLaunchingWithOptions
. The saveToURL
half of the if-statement gets called initially, and returns a success. Then in the following few calls the openWithCompletionHandler:
gets called, and returns successfully.
However, at some point after using the app for awhile, the openWithCompletionHandler:
returns success = FALSE. I am not sure why, or how the UIManagedDocument
gets messed up. The URL still seems to be the same, and the fileExistsAtPath
is still returning YES
.
Does anyone know why this might be happening? Or if there is a way for me to debug and find out what the actual error is that is causing the open to fail?