2014-04-16 33 views
1

我在我的View中有2個按鈕。 fetchstop按鈕。當我按fetch按鈕我的方法獲取數據並將其放到textView的文本。但如果我按stop按鈕,我想停止提取。我知道我無法停止請求,但是當我按stop按鈕時,它不能更改textView的文本。爲了更清楚地獲取數據,我的程序一定不能回來。
這裏是我的fetch方法:如何停止提取?

- (void) pressedFetch 
{ 
    dispatch_async(dispatch_get_main_queue(), ^{ 
     textView.text = [NSString stringWithFormat:@"%@", [self fetchJson]]; 
    }); 
} 

我想喜歡callBack的方法來做到這一點。我怎樣才能做到這一點?

回答

0

其實這是錯誤的方式。我改變了我的方法。我用NSURLSession做了。它有一個名爲invalidateAndCancel的方法。如果我使用這種方法,我的session被取消,並且fetching被停用。

- (void) pressedFetch 
{ 
    NSString *jsonUrl = @"http://api.geonames.org/postalCodeLookupJSON?postalcode=6600&country=AT&username=demo"; 
NSURL *url = [NSURL URLWithString:str]; 
NSURLSessionConfiguration *conf = [NSURLSessionConfiguration ephemeralSessionConfiguration]; 
    session = [NSURLSession 
       sessionWithConfiguration:conf 
       delegate:self 
       delegateQueue:[NSOperationQueue mainQueue]]; 
    task = [session downloadTaskWithRequest:request]; //NSURLSessionDownloadTask *task = ... 
    [task resume]; 
} 

- (void) pressedStop 
{ 
    [session invalidateAndCancel]; //NSURLSession *session = ... 
} 

它是那麼容易)))

+0

當然,那麼你可以通過使用'NSURLSessionDownloadDelegate'的方法獲取數據 –

2

請勿使用GCD,請使用更高級別的NSOperation提供取消支持的API。在您的操作子類中,您可以在使用下載的數據之前檢查被取消的操作。取消您使用操作隊列cancelAllOperations的方法。

你的操作可能是NSBlockOperation一個實例,並假設fetchJson是同步的,是這樣的:

NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{ 
    id json = [self fetchJson]; 

    if (![self isCancelled]) { 
     dispatch_async(dispatch_get_main_queue(), ^{ 
      textView.text = [NSString stringWithFormat:@"%@", json]; 
     }); 
    } 
}]; 
+0

u能解釋清楚?在我'pressed的停頓'方法中,我想取消這個'操作'來回來。不想檢查改變textView –

+1

@韋恩是正確的。 'NSOperationQueue'是正確的方法。創建一個'NSOperationQueue'屬性,將其合成。在開始操作時,不是啓動它,而是隻添加'operationQueue':'[myOperationQueue addOperation:myOperation];'。這取決於您的請求,無論是塊操作還是請求操作。在cancelButton目標方法中,使用以下命令取消請求:'[myOperationQueue cancelAllOperations];' – n00bProgrammer

1

如果你只是不想顯示在敲擊停止按鈕所取得的數據,

- (IBAction)stop:(id)sender 
{ 
    textView.text = @"" 
} 

,或者如果你正在使用NSURLConnection的獲取來自服務器的數據,你可以調用它

- (IBAction)stop:(id)sender 
{ 
    [urlConnection cancel]; // NSURLConnection *connection; 
    /* After this method is called, the connection’s delegate no longer receives any messages for the connection. If you want to reattempt the connection, you should create a new connection object.*/ 
} 
取消
+0

我的目標是取消'fetching operation',而不是將'TextView'的文本更改爲空。我不能取消連接 –

+0

然後你可以去NSURLConnection並調用取消它。 – keshav

0

首先,您必須檢查您的班級中是否已下載數據。 如果不是,你可以下載數據並通過檔案存儲在一個文件目錄中,下次檢查它在文件目錄中是否可用,並將你的數據解除存檔並使用它。