2012-12-16 33 views
1

我該如何一次運行我的代碼。也就是說,我有一個想要一致執行的代碼。例如:Objective-c中的隊列

- (IBAction)downloadPressed:(id)sender { 
    //1 
    CGRect frameDelete = deleteButton.frame; 
    frameDelete.origin.y = (deleteButton.frame.origin.y-50); 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration: 0.5]; 
    deleteButton.frame = frameDelete; 
    [UIView commitAnimations]; 
    [progressLine setProgress:0]; 

    //2 Wait until the code is executed above, and then run the code below  
    NSURL *fileURL = [NSURL URLWithString:@"http://intercreate.ru/all.zip"]; 
    [self downloadDataAtURL:fileURL]; 

    //3 Wait until the code is executed above, and then run the code below 
    CGRect frameDelete1 = deleteButton.frame; 
    frameDelete1.origin.y = (deleteButton.frame.origin.y+50); 
    [UIView beginAnimations:nil context:nil]; 
    [UIView setAnimationDuration: 0.5]; 
    deleteButton.frame = frameDelete1; 

} 

也就是說,我希望我的代碼被分爲三個部分:

  1. 先動旋鈕向上
  2. 下載文件
  3. 回落按鈕。

我該怎麼做?

回答

1

傳統的做這種事情的方式是協議/委託設計模式。然而,這是因爲塊而過時的。他們是完成這個最簡單的方法。例如,它們內置於優秀的MBProgressHUD。你可以用這個完成你想要的:

- (IBAction)downloadPressed:(id)sender { 
CGRect frameDelete = deleteButton.frame; 
frameDelete.origin.y = (deleteButton.frame.origin.y-50); 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration: 0.5]; 
deleteButton.frame = frameDelete; 
[UIView commitAnimations]; 
[progressLine setProgress:0]; 

MBProgressHUD *aHud = [[MBProgressHUD alloc] initWithView:self.view]; 
[aHud showHudAnimated: NO whileExecutingBlock:^ 
{ 
//2 Wait until the code is executed above, and then run the code below  
NSURL *fileURL = [NSURL URLWithString:@"http://intercreate.ru/all.zip"]; 
[self downloadDataAtURL:fileURL]; 
} completionBlock:^
    { 
//3 Wait until the code is executed above, and then run the code below 
CGRect frameDelete1 = deleteButton.frame; 
frameDelete1.origin.y = (deleteButton.frame.origin.y+50); 
[UIView beginAnimations:nil context:nil]; 
[UIView setAnimationDuration: 0.5]; 
deleteButton.frame = frameDelete1; 
[UIView commitAnimations]; 

}]; }

Progress HUD可以做得更多,例如,顯示進度指標:)

退房這個職位塊使用:link

1

上半年可以被打倒新的基於塊的動畫,可以提供被執行一段代碼在動畫完成時。第二部分我肯定會使用通知,當文件完成下載時,您可以發佈通知,然後您的代碼的任何其他部分都可以以任何他們想要的方式響應此事件,更改GUI,通知用戶,刪除要下載的東西列表,您還可以添加新的東西來收聽此通知,而不需要更改原始代碼。

0

您似乎正在使用舊式beginAnimationscommitAnimations方法。

如果您轉移到基於塊的新動畫方法,則可以使用完成處理程序塊的優勢,並且如果使用異步URL下載方法,則API還提供了一個添加完成塊的位置。

所以,基本上是:

  1. 創建一個基於塊的動畫動按鈕
  2. 在這個動畫的完成處理程序觸發一個異步下載
  3. 在下載火災的動畫完成處理移動按鈕。

因爲這些都是在一個基於塊的方法(原始動畫塊)中,所以單個動作會一個接一個地發生。