Почему ASINetworkQueue и ASIHTTPRequest блокируют основной поток? - PullRequest
1 голос
/ 30 декабря 2011

Когда это работает, мой пользовательский интерфейс зависает.Это довольно много из документов:

- (void)doNetworkOperations
{
    [[self networkQueue] cancelAllOperations];

    [self setNetworkQueue:[ASINetworkQueue queue]];
    [[self networkQueue] setMaxConcurrentOperationCount:8];
    [[self networkQueue] setDelegate:self];
    [[self networkQueue] setRequestDidFinishSelector:@selector(requestFinished:)];
    [[self networkQueue] setQueueDidFinishSelector:@selector(queueFinished:)];
    [[self networkQueue] setRequestDidFailSelector:@selector(requestFailed:)];


    ASIHTTPRequest *request01 = [self loadTodaysNews];
    ASIHTTPRequest *request02 =  [self loadFoodItems];
    ASIHTTPRequest *request03 = [self loadFarms];
    ASIHTTPRequest *request04 = [self loadMobileSections];
    ASIHTTPRequest *request05 = [self loadThymeLinks];
    ASIHTTPRequest *request06 = [self loadFoodCategories];
    ASIHTTPRequest *request07 = [self deleteDeletedRecords];


    [[self networkQueue] addOperation:request01];
    [[self networkQueue] addOperation:request02];
    [[self networkQueue] addOperation:request03];
    [[self networkQueue] addOperation:request04];
    [[self networkQueue] addOperation:request05];
    [[self networkQueue] addOperation:request06];
    [[self networkQueue] addOperation:request07];

    [[self networkQueue] go];
}

и вот пример запроса:

- (ASIHTTPRequest *) loadTodaysNews
{   
    NSString* urlString = @"http://xxx.xxx.xxx/ra/NewsItem.json";
    // 0. Setup URL
    if(self.settings.lastNewsTimestamp != nil){
        [NSDateFormatter setDefaultFormatterBehavior:NSDateFormatterBehavior10_4];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"MMddyyHHmm"];

        urlString=[urlString stringByAppendingFormat:@"?lastmoddate=%@", [dateFormatter stringFromDate:self.settings.lastNewsTimestamp]]; 
        [dateFormatter release];        
    }



    // 1. Fetch
      NSURL* url = [NSURL URLWithString:urlString];
    ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];


    [request setCompletionBlock:^(void) {
        [NSThread detachNewThreadSelector: @selector(spinBegin) toTarget:self withObject:nil];


        NSString *responseString = [request responseString];
        // 3. parse the response
        NSArray *responseDict = [responseString objectFromJSONString];

        for(int i=0;i<responseDict.count;i++){
            NSDictionary *itemDict = (NSDictionary *)[responseDict objectAtIndex:i];


            NSPredicate* predicate =  [NSPredicate predicateWithFormat:@"(extID == %@)", [[itemDict objectForKey:@"id"]description]];
            NSMutableArray * mutableFetchResults = [CoreDataHelper searchObjectsInContext:@"NewsItem" :predicate:@"name" :YES :   self.managedObjectContext];

            NewsItem* item  = nil;
            if(mutableFetchResults == nil || mutableFetchResults.count == 0){
                item = [NSEntityDescription
                                   insertNewObjectForEntityForName:@"NewsItem"
                                   inManagedObjectContext:self.managedObjectContext];

            } else {
                //Edit or Delete
                item = [mutableFetchResults objectAtIndex:0];
            }
            if([[[itemDict objectForKey:@"publish"]description]isEqualToString:@"1"]){
                //edit

                item.name = [itemDict objectForKey:@"name"];
                item.textDescription = [itemDict objectForKey:@"textDescription"];
                if([itemDict objectForKey:@"newsCategory"]!= [NSNull null]){
                    item.section = [[itemDict objectForKey:@"newsCategory"] objectForKey:@"name"];
                }

                item.timeStamp = [NSDate date];
            }else{
                //unpublish/delete
                [self.managedObjectContext deleteObject:item];

            }
        }
        NSError* error = nil;
        if (![self.managedObjectContext save:&error]) {
            NSLog(@"Error %@",error);
        }

        //send a reload message?
        [self.newsViewController.tableView reloadData];
        [NSThread detachNewThreadSelector: @selector(spinEnd) toTarget:self withObject:nil];

    }];

    return request;

//    [request startAsynchronous];
}

Чего мне не хватает?Спасибо

1 Ответ

3 голосов
/ 30 декабря 2011

Важно то, что вы должны выполнять только действия пользовательского интерфейса над основной цепью!

может быть, это может помочь:

[self.newsViewController.tableView performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...