2012-11-22 37 views
-2

我不知道如何停止IBAction。我需要的:我按下按鈕,然後調用運行約5分鐘的IBAction。我想使取消按鈕,按下時,將停止從第一個按鈕IBAction。停止從另一個按鈕的IBAction Objective-C

我該怎麼做?

代碼:

- (IBAction)download:(id)sender { 


    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0),^{ 

     // Determile cache file path 
     NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 


     for (i=0;i<=7;i++) { 

      //Updating progressView and progressLabel 

      dispatch_async(dispatch_get_main_queue(),^{ 
       progressSlider.progress = (float)i/(float)299; 
       progressLabel.text = [NSString stringWithFormat:@"Загружено: %d из 299",i]; 
      }); 

      NSString *filePath = [NSString stringWithFormat:@"%@/avto-0-%d.html", [paths objectAtIndex:0],i]; 

      // Download and write to file 
      NSString *mustUrl = [NSString stringWithFormat:@"http://www.mosgortrans.org/pass3/shedule.php?type=avto&%@", [listOfAvtoUrl objectAtIndex:i]]; 
      NSURL *url = [NSURL URLWithString:mustUrl]; 
      NSData *urlData = [NSData dataWithContentsOfURL:url]; 


      [urlData writeToFile:filePath atomically:YES]; 

     } 

    }); 


} 
+0

爲什麼它運行5分鐘?顯示該功能的代碼 –

+0

...以及*運行5分鐘的內容。如果它是在自己的線程中運行的代碼,那會影響我們的答案。 –

+0

請不要生氣,我只是在學習 – IlyaKharlamov

回答

1

調用運行在一個單獨的線程代碼時IBAction點擊其他功能。現在您可以根據需要停止/取消線程。

0

創建一個名爲isCancelled的BOOL變量。當你點擊另一個按鈕isCancelled爲YES。在你的下載功能裏面設置這個循環:

if (isCancelled)return;