4
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Create and run operation using

NSOperation *op = [NSBlockOperation ... your block...];
[[NSOperationQueue new] addOperation: op];

and instead of using a runloop, wait for the result:

[op waitUntilFinished];
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.