我正在使用单例模式来访问我的应用程序中唯一的 UIManagedDocument。一切正常,除了单例中的完成块永远不会执行。
ManagedDocumentHelper.m
:
+ (UIManagedDocument *) sharedDatabaseUsingBlock:(completion_block_t) completionBlock
{
NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
url = [url URLByAppendingPathComponent:@"database"];
static UIManagedDocument *managedDocument;
static dispatch_once_t mngddoc;
// synchronous
dispatch_once(&mngddoc, ^{
managedDocument = [[UIManagedDocument alloc] initWithFileURL:url];
if (![[NSFileManager defaultManager] fileExistsAtPath:[url path]]){
NSLog(@"Creating...");
[managedDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating completionHandler:^(BOOL success){
NSLog(@"Created!");
completionBlock(managedDocument);
}];
} else if(managedDocument.documentState == UIDocumentStateClosed){
NSLog(@"Openning..."); //EXECUTED!
[managedDocument openWithCompletionHandler:^(BOOL success){
if(success){
NSLog(@"Open!"); //EXECUTED!
completionBlock(managedDocument); //NOT NIL
}
}];
} else if(managedDocument.documentState == UIDocumentStateNormal){
completionBlock(managedDocument);
}
});
return (UIManagedDocument *) managedDocument;
}
和typedef void (^completion_block_t)(UIManagedDocument *document);
在我的控制器内部:
@interface MyViewContoller()
{
UIManagedDocument *_database;
}
@end
@implementation MyViewContoller
- (void) initializeDataBase
{
if(!_database){
_database = [ManagedDocumentHelper sharedDatabaseUsingBlock:^(UIManagedDocument *document){
NSLog(@"DATABASE LOADED!! %@", document); // NEVER EXECUTED :(
}];
}
}
非常感谢!