patternMinor
Is there a better way to make sure a variable is initialized when using blocks?
Viewed 0 times
initializedblocksmakewaybettersureusingwhentherevariable
Problem
I have a method to provide an
Any suggestion will be appreciated.
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.
Solution
Create and run operation using
and instead of using a runloop, wait for the result:
NSOperation *op = [NSBlockOperation ... your block...];
[[NSOperationQueue new] addOperation: op];and instead of using a runloop, wait for the result:
[op waitUntilFinished];Code Snippets
NSOperation *op = [NSBlockOperation ... your block...];
[[NSOperationQueue new] addOperation: op];[op waitUntilFinished];Context
StackExchange Code Review Q#32324, answer score: 2
Revisions (0)
No revisions yet.