0

我正在使用单例模式来访问我的应用程序中唯一的 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 :(
        }];
    }
}

非常感谢!

4

2 回答 2

0

The problem was that in a previous controller I was accessing the UIManagedDocument as well with the singleton and this created some kind of conflict with this access. Maybe the previous block was still in memory and this newer one was never called.

于 2013-11-08T19:09:31.927 回答
0

您确定在所有情况下都会调用 completionBlock(managedDocument) 吗?你试过断点吗?

MySingleton.h

typedef void (^completion_block_t)(UIManagedDocument *document);

@interface MySingleton : NSObject

+ (instancetype)sharedInstanceWithCompletion:(completion_block_t)block;

@end

MySingleton.m

#import "MySingleton.h"

@implementation MySingleton

+ (instancetype)sharedInstanceWithCompletion:(completion_block_t)block
{
    static dispatch_once_t token;
    static MySingleton *instance;
    dispatch_once(&token, ^{
        instance = [[MySingleton alloc] init];
    });
    block(nil);
    return instance;
}

@end

以及您想要的任何地方:

[MySingleton sharedInstanceWithCompletion:^(UIManagedDocument *document) {
    NSLog(@"Done");
}];

为我工作。

于 2013-11-08T17:35:01.593 回答