2014-10-01 2 views
0

В настоящее время я использую dispatch_group, чтобы получать уведомления, когда все параллельные задачи выполняются. Я переношу некоторые тяжелые задачи в одну параллельную очередь в методе класса [TWReaderDocument documentFileURL: url withCompletionBlock:].Не получать уведомление dispatch_group_notify

Я внедрил следующий код, но не получил никакого уведомления. Я не понимаю, что я делаю неправильно, потенциально в коде ниже:

dispatch_group_t readingGroup = dispatch_group_create(); 

    NSFileManager* manager = [NSFileManager defaultManager]; 

    NSString *docsDir = [[[NSBundle mainBundle] resourcePath] stringByAppendingPathComponent:@"Data"]; 

    NSDirectoryEnumerator *dirEnumerator = [manager enumeratorAtURL:[NSURL fileURLWithPath:docsDir] 
             includingPropertiesForKeys:[NSArray arrayWithObjects:NSURLNameKey, 
                    NSURLIsDirectoryKey,nil] 
                  options:NSDirectoryEnumerationSkipsHiddenFiles 
                 errorHandler:nil]; 


    // An array to store the all the enumerated file names in 
    NSMutableArray *arrayFiles; 

    // Enumerate the dirEnumerator results, each value is stored in allURLs 
    for (NSURL *url in dirEnumerator) { 

     // Retrieve the file name. From NSURLNameKey, cached during the enumeration. 
     NSString *fileName; 
     [url getResourceValue:&fileName forKey:NSURLNameKey error:NULL]; 

     // Retrieve whether a directory. From NSURLIsDirectoryKey, also cached during the enumeration. 
     NSNumber *isDirectory; 
     [url getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:NULL]; 


     if (![isDirectory boolValue]) { 

       dispatch_group_enter(readingGroup); 
       TWReaderDocument* doc = [TWReaderDocument documentFileURL:url withCompletionBlock:^(BOOL success) { 

        dispatch_group_leave(readingGroup); 

       }]; 

       [arrayFiles addObject:doc]; 

     } 
     else if ([[[fileName componentsSeparatedByString:@"_" ] objectAtIndex:0] isEqualToString:@"XXXXXX"]) { 

      TreeItem* treeItem = [[TreeItem alloc] init]; 

      arrayFiles = [NSMutableArray arrayWithCapacity:10]; 

      treeItem.child = arrayFiles; 
      treeItem.nodeName = [[fileName componentsSeparatedByString:@"_" ] lastObject]; 
      [self addItem:treeItem]; 


     } 
    } 

    dispatch_group_notify(readingGroup, dispatch_get_main_queue(), ^{ // 4 

     NSLog(@"All concurrent tasks completed"); 

    }); 

ли в dispatch_group_enter и dispatch_group_leave должны быть выполнены в том же потоке?

EDIT фрагмент кода моего фабричный метод может помочь как хорошо:

+ (TWReaderDocument *)documentFileURL:(NSURL *)url withCompletionBlock:(readingCompletionBlock)completionBlock{ 


      TWReaderDocument * twDoc = [[TWReaderDocument alloc] init]; 
      twDoc.status = ReaderDocCreated; 

      twDoc.doc = [ReaderDocument withDocumentFilePath:[url path] withURL:url withLoadingCompletionBLock:^(BOOL completed) { 

       twDoc.status = completed ? ReaderDocReady : ReaderDocFailed; 

       completionBlock(completed); 

      }]; 

      return twDoc; 

     } 

TWReaderDocument класс-обертка, которое называют внутренне следующие методы библиотеки третьих сторон (это читатель PDF)

+ (ReaderDocument *)withDocumentFilePath:(NSString *)filePath withURL:(NSURL*)url withLoadingCompletionBLock:(readingCompletionBlock)completionBlock{ 

    ReaderDocument *document = [[ReaderDocument alloc] initWithFilePath:filePath withURL:url withLoadingCompletionBLock:[completionBlock copy]]; 
    return document; 
} 


- (id)initWithFilePath:(NSString *)fullFilePath withURL:(NSURL*)url withLoadingCompletionBLock:(readingCompletionBlock)completionBlock { 
    id object = nil; // ReaderDocument object; 

    if ([ReaderDocument isPDF:fullFilePath] == YES) // File must exist 
    { 
     if ((self = [super init])) // Initialize superclass object first 
     { 

      _fileName = [ReaderDocument relativeApplicationFilePath:fullFilePath]; // File name 

      dispatch_async([ReaderDocument concurrentLoadingQueue], ^{ 

       self.guid = [ReaderDocument GUID]; // Create a document GUID 

       self.password = nil; // Keep copy of any document password 

       self.bookmarks = [NSMutableIndexSet indexSet]; // Bookmarked pages index set 

       self.pageNumber = [NSNumber numberWithInteger:1]; // Start on page 1 

       CFURLRef docURLRef = (__bridge CFURLRef)url;// CFURLRef from NSURL 
       self.fileURL = url; 

       CGPDFDocumentRef thePDFDocRef = CGPDFDocumentCreateX(docURLRef, self.password); 

       BOOL success; 
       if (thePDFDocRef != NULL) // Get the number of pages in the document 
       { 
        NSInteger pageCount = CGPDFDocumentGetNumberOfPages(thePDFDocRef); 

        self.pageCount = [NSNumber numberWithInteger:pageCount]; 

        CGPDFDocumentRelease(thePDFDocRef); // Cleanup 

        success = YES; 
       } 
       else // Cupertino, we have a problem with the document 
       { 
//     NSAssert(NO, @"CGPDFDocumentRef == NULL"); 
        success = NO; 
       } 


       NSFileManager *fileManager = [NSFileManager new]; // File manager instance 

       self.lastOpen = [NSDate dateWithTimeIntervalSinceReferenceDate:0.0]; // Last opened 

       NSDictionary *fileAttributes = [fileManager attributesOfItemAtPath:fullFilePath error:NULL]; 

       self.fileDate = [fileAttributes objectForKey:NSFileModificationDate]; // File date 

       self.fileSize = [fileAttributes objectForKey:NSFileSize]; // File size (bytes) 

       completionBlock(success); 

      }); 


      //[self saveReaderDocument]; // Save the ReaderDocument object 

      object = self; // Return initialized ReaderDocument object 
     } 
    } 

    return object; 
} 

ответ

1

трудно сказать, что здесь происходит, не зная больше о TWReaderDocument, но у меня есть подозрение ...

Прежде всего, нет, dispatch_group_enter и dispatch_group_leave do не должны быть выполнены в той же теме. Точно нет.

Мое лучшее предположение, основанное на информации здесь, было бы для ввода, [TWReaderDocument documentFileURL:withCompletionBlock:] возвращает nil. Вместо этого вы можете попробовать:

if (![isDirectory boolValue]) { 

      dispatch_group_enter(readingGroup); 
      TWReaderDocument* doc = [TWReaderDocument documentFileURL:url withCompletionBlock:^(BOOL success) { 

       dispatch_group_leave(readingGroup); 

      }]; 

      // If the doc wasn't created, leave might never be called. 
      if (nil == doc) { 
       dispatch_group_leave(readingGroup); 
      } 

      [arrayFiles addObject:doc]; 

    } 

Дайте это попробовать.

EDIT: Это точно, как я ожидал. Есть случаи, когда этот заводский метод не будет называть завершение. Например:

if ([ReaderDocument isPDF:fullFilePath] == YES) // File must exist 

Если -isPDF: возвращает NOcompletionBlock никогда не будет называться, а возвращаемое значение будет nil.

Кстати, вы никогда не должны сравнивать что-то == YES. (Что-то отличное от нуля эквивалентно YES, но YES определяется как 1. Вобще if ([ReaderDocument isPDF:fullFilePath]). Это эквивалентно, и безопаснее.

+0

документ фактически ноль при вызове в блоке завершения, но почему же он связан с dispatch_group_leave? – tiguero

+0

Что Я говорю, что это выглядит так: '- [TWReaderDocument documentFileURL: withCompletionBlock:]' фактически является фабричным методом, возвращая новый экземпляр 'TWReaderDocument'. Если по какой-либо причине экземпляр не создается,' completeBlock' может никогда Как уже было сказано, невозможно знать, не зная больше о внутренних компонентах «TWReaderDocument». - Чтобы рассуждать с другой стороны: если ваш 'dispatch_group_notify' не вызван, то один или несколько экземпляров' dispatch_group_leave' являются * тоже * не назывался. – ipmcc

+0

см. Мое редактирование. Я выставил свой заводский метод: он довольно длинный ... Btw doc - всего лишь нуль в блоке завершения, а не снаружи. – tiguero

Смежные вопросы