0

同期メソッドで Web サービスからデータを取得しています。Web サービスにリクエストを送信してから、フリーズを表示します。Web サービスからデータをロードする前に UIActivityIndi​​catorView を追加しようとしましたが、データを取得した後に停止しましたが、アクティビティ インジケーターが表示されません。Web サービスのデータ フェッチ操作を別のスレッドに配置しようとしました

[NSThread detachNewThreadSelector:@selector(fetchRequest) toTarget:self withObject:nil];

ただし、現時点では、セルを描画するためのデータを取得できないため、TableView がクラッシュします。私がやっているfetchRequest関数で

        NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL
                                                          URLWithString:URLString]];
        NSData *response = [NSURLConnection sendSynchronousRequest:request
                                             returningResponse:nil error:nil];

        NSError *jsonParsingError = nil;
        NSDictionary *tableData = [NSJSONSerialization JSONObjectWithData:response
                                                              options:0
                                                                error:&jsonParsingError];


        responseArray = [[NSMutableArray alloc]initWithArray:[tableData objectForKey:@"data"]];

        for(int i = 0; i < responseArray.count; i++)
        {
            NSArray * tempArray = responseArray[i];
            responseArray[i] = [tempArray mutableCopy];
        }

これresponseArrayは、セルに情報を入力するために使用されます。これを行う方法を教えてください。どんな助けでも大歓迎です...

4

2 に答える 2

2

問題はあなたのアプローチにあります。Synchronousメソッドはメインスレッドで実行されます。また、メイン スレッドで UI が更新されるため、アプリがハングします。

したがって、解決策は、asynchronousメソッドを使用して別のスレッドでデータをダウンロードし、UI がハングしないようにすることです。

したがって、 を使用しNSURLConnectionますsendAsynchronousRequest。サンプルコードは次のとおりです。

NSURL *url = [NSURL URLWithString:@"YOUR_URL_HERE"];

NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
NSOperationQueue *queue = [[NSOperationQueue alloc] init];

[NSURLConnection sendAsynchronousRequest:urlRequest queue:queue completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
    //this is called once the download or whatever completes. So you can choose to populate the TableView or stopping the IndicatorView from a method call to an asynchronous method to do so.
}]; 
于 2013-11-02T09:38:32.577 に答える
1

グランド セントラル ディスパッチを使用して次のようにデータをフェッチし、バックグラウンド キューにディスパッチして、UI の更新にも使用されるメイン スレッドをブロックしないようにすることをお勧めします。

 dispatch_queue_t myqueue = dispatch_queue_create("myqueue", NULL);
    dispatch_async(myqueue, ^(void) {

    [self fetchRequest];
 dispatch_async(dispatch_get_main_queue(), ^{
            // Update UI on main queue
 [self.tableView reloadData];
        });

    });

解析の開始時に使用できるアクティビティ インジケーターについては、次のとおりです。

[self.activityIndicator startAnimating];
self.activityIndicator.hidesWhenStopped = YES

そして、テーブルがデータで満たされている場合:

[self.activityIndicator stopAnimating];
于 2013-11-02T09:40:30.740 に答える