我正在尝试设计一个辅助方法,它将检索 UIManagedDocument,然后打开并返回它,以便我可以从我的应用程序中的多个位置访问相同的 UIManagedDocument。
由于我对块不太熟悉,因此我对此的异步性质有疑问。理想情况下,事件的顺序是这样的:
- X 类调用帮助器方法来检索 UIManagedDocument,并包含在返回打开的文档时运行的代码块。
- 类方法检索 UIManagedDocument 并在必要时调用 openWithCompletionHandler 或 saveToURL,并包含在返回打开的文档时运行的代码块。
- openwithCompletionHandler 或 saveToURL 完成他们的任务,并返回 success = 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
}];
}
}