簡體   English   中英

調度無法正常工作

[英]Dispatch doesn't work properly

我嘗試在后台獲取一些數據並在搜索欄中鍵入內容時刷新表格視圖,這是我當前的代碼:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        Games * game = [[Games alloc] init];
        NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
        self.searchArray = [temp valueForKey:@"results"];
        [self.tableView reloadData];
    });
}

我究竟做錯了什么? 如果我在搜索欄中再輸入一個單詞,或者點擊“取消”按鈕,它就會刷新,並且數據會顯示在表格視圖中。

調用[self.tableView reloadData]; 必須在主線程上。 更換線

[self.tableView reloadData];

dispatch_async(dispatch_get_main_queue(), ^{
    [self.tableView reloadData];
});

在主線程中,您正在創建后台線程,在進行任何處理之后,您需要切換到主線程以更新UI。

例如,您可以按照以下方法進行編碼:

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    // [activityIndicator startAnimating];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

        // do your background code here
        Games * game = [[Games alloc] init];
        NSArray * temp = [game comingSoonWithPlatform:@"pc" header:[game gameHeader] parseLink:[game gameComingSoonListLinkWithPlatform:@"pc"]];
        self.searchArray = [temp valueForKey:@"results"];

        dispatch_sync(dispatch_get_main_queue(), ^{
            // you are now on the main queue again, update ui here  
        //[activityIndicator stopAnimating];
        [self.tableView reloadData];
        });
    });
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM