Search This Blog

Sunday, 26 August 2012

How to use Multithreading to fetch data in xcode and prevent ur app from freezing

Hello Friends,
                       It was strange that i used it before , but in an interview i was asked about Lazy loading...and i was stupid enough and thought it is something new i never ever used....Actually what it means is to load your data usng a different thread and not in main thread to prevent your app from freezing this is what they call ...LAZY LOADING!!! ....Here is the code to run a separate thread from main thread and you can do your data fetching and other bulky work in these threads and your app will remain working as it is ...and display the data once it is available...


-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [loading setHidden:NO];
    [loading startAnimating];
    [warning setHidden:NO];
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
      AppDelegate *app = (AppDelegate *)[[UIApplication sharedApplication]delegate];
    radioStations.userInteractionEnabled = NO;
    favButton.userInteractionEnabled = NO;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSString *add1URL = @"";
        NSString *add2URL = @"";
        NSString *add3URL = @"";
        NSData *data1 = [NSData dataWithContentsOfURL:[NSURL URLWithString:add1URL]];
        NSData *data2 = [NSData dataWithContentsOfURL:[NSURL URLWithString:add2URL]];
        NSData *data3=    [NSData dataWithContentsOfURL:[NSURL URLWithString:add3URL]];
        app.addimg1 = [UIImage imageWithData:data1];
        app.addimg2 = [UIImage imageWithData:data2];
        app.addimg3 = [UIImage imageWithData:data3];
    [loading stopAnimating];
    app.preScreen = @"All";
    UIStoryboard *story = self.storyboard;
    NSString *url = (NSString *)[urls objectAtIndex:indexPath.row];
    player = [story instantiateViewControllerWithIdentifier:@"Radioplayer"]; = (NSString *)[station objectAtIndex:indexPath.row];
    player.title = url;
    app.genre = cell.detailTextLabel.text;
    [self presentViewController:player animated:YES completion:nil];

I used the simplest way for non confusing example here, i am running a different thread as you can see this thread will keep running in background and fetch the images whereas my main thread will keep running and push the player view on screen

Ask for any queries there are lot of tutorials on web but i found them confusing the basic concept is this only.....that you run a different thread fetch data and when the data will b available ,it will b shown on display that's it for now....SIGNING OFF!!!

No comments:

Post a Comment