I have a method to provide an NSManagedObjectContext
using UIManagedDocument
. I need to ensure that the context
did initialize before I return, so I added an infinite while loop at the end of the method. But I think that was very stupid and is not acceptable.
- (NSManagedObjectContext *)context {
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"Test"];
UIManagedDocument *document = [[UIManagedDocument alloc] initWithFileURL:url];
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]) {
[document saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = document.managedObjectContext;
}
else {
NSLog(@"[%@ %@] FATAL Error CANNOT create DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
exit(1);
}
}];
}
else if (document.documentState == UIDocumentStateClosed) {
[document openWithCompletionHandler:^(BOOL success) {
if (success) {
self.managedObjectContext = document.managedObjectContext;
}
else {
NSLog(@"[%@ %@] FATAL Error CANNOT open DB", NSStringFromClass([self class]), NSStringFromSelector(_cmd));
exit(1);
}
}];
}
else {
self.managedObjectContext = document.managedObjectContext;
}
while (!self.managedObjectContext) {
// Is there any way better?
NSDate *futureTime = [NSDate dateWithTimeIntervalSinceNow:1];
[[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode beforeDate:futureTime];
}
return self.managedObjectContext;
}
Any suggestion will be appreciated.