简体   繁体   中英

GCD going back to main thread

In my application I load information from several (6-10) websites using NSXMLParser and then load the information into views.

Right now, my applications is set up so that it loops through the sites in viewDidLoad in my main view controller and loads them each in a background thread that I created. It does this in a background thread so that the user does not have to wait for all of the sites to load before the view loads.

for (NSMutableDictionary *dict in self.sitesArray) {
    SiteData *data = [[SiteData alloc] init];
    [data setDelegate:self];
    dispatch_async(backgroundQueue, ^(void) {
        [data loadSite:[dict objectForKey:@"SiteName"]];
    });

}

In SiteData, I load the site using NSXMLParser (all of the delegate methods also implemented properly)

-(void)loadSite:(NSString *)site{
    NSXMLParser *parser = [[NSXMLParser alloc] initWithContentsOfURL:[self fullURLForSiteName:site]];
    [parser setDelegate:self];
    [parser parse];
    return;
}

When the NSXMLParser has finished the document and the SiteData instance is populated with the site's data, it passes itself to a method in my main view controller on the main thread.

- (void)parserDidEndDocument:(NSXMLParser *)parser{    
    dispatch_async(dispatch_get_main_queue(), ^(void) {
         [delegate successfullyLoadedSite:self];
    });
}

successfullyLoadedSite: loads the passed site's data into a view and displays it to the user. Note that multiple site's data are displayed on the same screen.

What I want to happen: I want each site's data to appear on the screen as it is loaded, not having to wait until all of them finish loading for the view to refresh.

What is happening: One of the sites loads and displays, then I have to wait for all of the rest to load, then all the rest get displayed at once.

From console logging it seems that once it calls successfullyLoadedSite: on the main queue the first time, everything gets run on the main queue. Once the first successfullyLoadedSite: on the main queue gets called, it loads all of the sites into objects, then loads them into views.

Any ideas what's going on? If you can't tell I'm new to multithreading. Thanks:)


Edit: I create backgroundQueue like this:

dispatch_queue_t backgroundQueue;

and in init

backgroundQueue = dispatch_queue_create("uni.que.identifier.bgqueue", NULL);

and release it in dealloc with:

dispatch_release(backgroundQueue);

The queue of using dispatch_queue_create function to create is serial queue, then dispatch_queue_create submitted block will execute as sequential order.

use:

dispatch_queue_t backgroundQueue =
    dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM