Как мне создать глобальный экземпляр UIManagedDocument для каждого документа на диске, совместно используемого всем моим приложением с использованием блоков?

Я пытаюсь разработать вспомогательный метод, который будет извлекать UIManagedDocument, затем открывать и возвращать его, чтобы я мог получить доступ к одному и тому же UIManagedDocument из нескольких мест в моем приложении.

У меня проблемы с асинхронным характером этого, поскольку я не слишком знаком с блоками.В идеале последовательность событий должна быть такой:

  1. Класс X вызывает вспомогательный метод для получения UIManagedDocument и включает блок кода для запуска при возврате открытого документа.
  2. Метод класса извлекает UIManagedDocument и при необходимости вызывает openWithCompletionHandler или saveToURL, а также включает блок кода для запуска при возврате открытого документа.
  3. openwithCompletionHandler или saveToURL завершают свою задачу и возвращаются с успехом = YES и запускают код в своем блоке
  4. Метод класса завершает свою задачу и возвращается с открытым 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
        }];

    }

}
11
задан Alan 9 February 2012 в 00:56
поделиться