我正在尝试设计一个帮助方法,它将检索UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序中的几个位置访问相同的UIManagedDocument。
我对这种异步性质有困难,因为我对块不太熟悉。理想情况下,事件的顺序是这样的:
- 类X调用helper方法来检索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
}];
}
}