2012-06-03 67 views
1

這裏是塊電話:完成塊的不予執行

[VacationHelper openVacationWithName:vacationName 
       usingBlock:^(UIManagedDocument *vacationDocument) { 
    NSLog(@"vacationDocument.description:%@", vacationDocument.description); 
}]; 

在接收方法的.H:

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

而在.M:

+ (void)openVacationWithName:(NSString *)vacationName 
        usingBlock:(completion_block_t)completionBlock; 
{ 
    NSLog(@"Opening Vacation Document"); 

    // Get documents directory and path. 
    NSURL *url = [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]; 
    url  = [url URLByAppendingPathComponent:vacationName]; 

    // Create the document and open if a match exists on file. 
    UIManagedDocument *vacationDocument = [[UIManagedDocument alloc] initWithFileURL:url]; 
    if ([[NSFileManager defaultManager] fileExistsAtPath:[url path]]) { 
     NSLog(@"vacationDocument.documentState:%i", vacationDocument.documentState); 
     [vacationDocument openWithCompletionHandler:^(BOOL success) { 
      if (success) NSLog(@"Document was opened."); 
      else NSLog (@"Couldn't open document at %@", url); 
     }]; 
    } else { 

     // No match exists, so save the document to file. 
     [vacationDocument saveToURL:url forSaveOperation:UIDocumentSaveForCreating 
        completionHandler:^(BOOL success) { 
         if (success) NSLog(@"Document was created."); 
         else NSLog(@"Couldn't create document at %@", url); 
        }]; 
    } 
    NSLog(@"Exiting helper."); 
} 

我問題是爲什麼執行沒有達到在openVacationWithName:調用中傳遞的塊?我從來沒有看到寫的NSLog。

我懷疑openVacationWithName:沒有完成,但NSLog的「退出幫助」。打印。任何指導讚賞。僅供參考iTunes U/Stanford CS193P作業#6。

回答

2

你不叫completionBlock裏面openVacationWithName:usingBlock:。也許你想在方法結束做到這一點:

... 
    if (completionBlock) { 
    completionBlock(vacationDocument); 
    } 

    NSLog(@"Exiting helper."); 
} 

(在這種情況下,也許會更有意義只返回UIManagedDocument

或者,也許裏面那些completionHandler S IN方法openWithCompletionHandler:saveToUrl:forSaveOperation:completionHandler:

... ^(BOOL success) { 
    if (success) { 
    NSLog(@"Document was created."); 
    } 
    else { 
    NSLog(@"Couldn't create document at %@", url); 
    } 

    if (completionBlock) { 
    completionBlock(vacationDocument); 
    } 
} ... 
+0

謝謝Jordão。我假定一旦被調用的方法完成,傳遞的塊將自動執行。正如你上面提到的那樣插入一個呼叫的工作。 ... completionBlock(vacationDocument); NSLog(@「Exiting helper。」); –

+0

我想在這裏提一下關於好的做法,wrap塊在if語句中調用:'if(block)block();',所以你的函數可以用nil完成處理程序調用,沒有例外。 – kelin

+0

感謝@kelin,你說得對,我會相應地更改代碼。 –