我试图设计一个辅助方法以检索UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序的多个位置访问同一个UIManagedDocument。
由于我对块不太熟悉,所以我遇到了异步性方面的困难。理想情况下,事件序列如下:
- 类X调用帮助方法来检索UIManagedDocument,并包括一段代码块在返回打开的文档时运行。
- 类方法检索UIManagedDocument并根据需要调用openWithCompletionHandler或saveToURL,并包括代码块以在返回打开的文档时运行。
- openwithCompletionHandler或saveToURL完成其任务,并以成功= YES返回并运行其代码块
- 类方法完成其任务并返回已打开的UIManagedDocument,并在其代码块中运行。
我能否通过某种方式传递原始块?
这是我的代码。非常感谢您的任何想法。
// This is a dictionary where the keys are "Vacations" and the objects are URLs to UIManagedDocuments
static NSMutableDictionary *managedDocumentDictionary = nil;
// This typedef has been defined in .h file:
// typedef void (^completion_block_t)(UIManagedDocument *vacation);
// The idea is that this class method will run the block when its UIManagedObject has opened
@implementation MyVacationsHelper
+ (void)openVacation:(NSString *)vacationName usingBlock:(completion_block_t)completionBlock
{
// Try to retrieve the relevant UIManagedDocument from managedDocumentDictionary
UIManagedDocument *doc = [managedDocumentDictionary objectForKey:vacationName];
// Get URL for this vacation -> "<Documents Directory>/<vacationName>"
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:vacationName];
// If UIManagedObject was not retrieved, create it
if (!doc) {
// Create UIManagedDocument with this URL
doc = [[UIManagedDocument alloc] initWithFileURL:url];
// Add to managedDocumentDictionary
[managedDocumentDictionary setObject:doc forKey:vacationName];
}
// If document exists on disk...
if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]])
{
[doc openWithCompletionHandler:^(BOOL success)
{
// Can I call the completionBlock from above in here?
// How do I pass back the opened UIDocument
}];
} else {
[doc saveToURL:url
forSaveOperation:UIDocumentSaveForCreating
completionHandler:^(BOOL success)
{
// As per comments above
}];
}
}