【发布时间】:2017-11-18 18:30:51
【问题描述】:
我正在使用UIManagedDocument 的子类在我的项目中使用Core Data。重点是让子类返回一个单例实例,以便我的屏幕可以简单地调用它,并且托管对象上下文对所有这些都保持相同。
在使用UIManagedDocument 之前,如果它的文件路径已经存在,我需要通过打开它来准备它,或者如果它还不存在则创建它。我在子类中创建了一个方便的方法prepareWithCompletionHandler: 来方便这两种情况。
@implementation SPRManagedDocument
// Singleton class method here. Then...
- (void)prepareWithCompletionHandler:(void (^)(BOOL))completionHandler
{
__block BOOL successful;
// _exists simply checks if the document exists at the given file path.
if (self.exists) {
[self openWithCompletionHandler:^(BOOL success) {
successful = success;
if (success) {
if (self.documentState != UIDocumentStateNormal) {
successful = NO;
}
}
completionHandler(successful);
}];
} else {
[self saveToURL:self.fileURL forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success) {
successful = success;
if (success) {
if (self.documentState != UIDocumentStateNormal) {
successful = NO;
}
}
completionHandler(successful);
}];
}
}
@end
我要做的是在我的应用程序委托的didFinishLaunchingWithOptions 中调用此准备方法,并等待在最后返回YES 或NO 之前执行完成块。我目前的方法行不通。
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
__block BOOL successful;
SPRManagedDocument *document = [SPRManagedDocument sharedDocument];
dispatch_group_t group = dispatch_group_create();
dispatch_group_async(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
[document prepareWithCompletionHandler:^(BOOL success) {
successful = success;
}];
});
dispatch_group_notify(group, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
});
return successful;
}
如何等到prepareWithCompletionHandler 中的完成处理程序被调用后再返回successful?我真的很困惑。
【问题讨论】:
-
另外,您为什么希望等待准备文件完成?您不使用launchOptions,也不需要向IOS报告是否处理了您的openURL请求。使用
- (void)applicationDidFinishLaunching:(UIApplication *)application,不要等待完成。 -
dispatch_group_notify不起作用,因为它只是安排一个块在组上的所有先前操作完成时执行,然后立即返回。dispatch_group_wait会如你所愿。
标签: ios objective-c grand-central-dispatch