2014-10-01 61 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_enterdispatch_group_leave必须是同一个线程上执行?

编辑 我的工厂方法的代码片段可能有助于藏汉:

+ (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_enterdispatch_group_leave不是必须在同一个线程上执行。当然不。

根据这里的信息,我最好的猜测是,对于某些输入,[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]; 

    } 

试试看。

编辑: 这完全如我所料。有些情况下,这种工厂方法不会调用完成。例如:

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

如果-isPDF:回报NOcompletionBlock将永远不会被调用,并且返回值将是nil

顺便说一句,你永远不应该比较一下东西== YES。 (任何非零相当于YES,但YES被定义为1。只是做if ([ReaderDocument isPDF:fullFilePath])。这相当于,更安全。

+0

文档实际上是在完成块中调用零,但为什么它涉及到dispatch_group_leave? – tiguero 2014-10-01 17:03:23

+0

什么我想说的是,它看起来像' - [TWReaderDocument documentFileURL:withCompletionBlock:]'实际上是一个工厂方法,它返回一个新的'TWReaderDocument'实例,如果由于某种原因没有创建实例,'completionBlock'可能永远不会如前所述,如果不知道更多关于TWReaderDocument内部的知识是不可能的 - 从另一方面来推断:如果你的dispatch_group_notify没有被调用,那么dispatch_group_leave的一个或多个实例是*还*不被称为 – ipmcc 2014-10-01 17:13:09

+0

看到我的编辑我已经暴露了我的工厂方法:它是相当长的...顺便说一句doc只是无完成块内没有外面。 – tiguero 2014-10-01 18:19:29