2013-02-15 56 views
3

當我確信兩個模塊代碼都已返回時,我該如何觸發一種方法?是這樣的...最後一個模塊返回時的觸發方法

// Retrieve Messages Array from Parse 
[ParseManager retrieveAllMessagesForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){ 
     self.messagesArray = objects; 
    }]; 

// Retrieve MessagesPermissions Array from Parse 
[ParseManager retrieveAllMessagePermissionsForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){ 
     self.messagePermissionsArray = objects; 
    }]; 

-(void)methodToRunWhenBothBlocksHaveReturned{ 
} 

回答

4

如果你能保證塊將在同一個線程(即UI線程)上執行,那麼選擇很簡單,使用__block變量。

-(void)yourMethod { 
    __block int count = 0; 
    [ParseManager retrieveAllMessagesForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){ 
     self.messagesArray = objects; 
     count++; 
     if (count == 2) { 
      [self methodToRunWhenBothBlocksHaveReturned]; 
     } 
    }]; 

    [ParseManager retrieveAllMessagePermissionsForShredderUser:(ShredderUser *)[PFUser currentUser] withCompletionBlock:^(BOOL success, NSError *error, NSArray *objects){ 
     self.messagePermissionsArray = objects; 
     count++; 
     if (count == 2) { 
      [self methodToRunWhenBothBlocksHaveReturned]; 
     } 
    }]; 
} 

-(void)methodToRunWhenBothBlocksHaveReturned{ 
} 

如果不具有相同的線程保證,你可以使用一個lock,以確保該變量(和比較2)的增量將是原子。

+0

正是我在找的,謝謝 – Alan 2013-02-16 22:43:32

相關問題