Search code examples
iosgrand-central-dispatchmbprogresshud

dispatch_async and frame rate


I'm trying to learn GCD, so I don't have a full grasp on how it works yet. For some reason, I experience a permanent drop in frame rate after I call the following method. If I don't use the dispatch functions and simply write the data on the main loop, the frame rate stays at 60. I don't know why.

-(void)saveDataFile {


        _hud = [MBProgressHUD showHUDAddedTo:self.parentView animated:YES];
        _hud.labelText = NSLocalizedString(@"Saving data...", nil);


        dispatch_queue_t myQueue = dispatch_queue_create("myQueueName", NULL);


        dispatch_async(myQueue, ^(void) {

            @autoreleasepool {

                id data = [self.model getData];
                if (data != nil) {

                    NSString *filePath = @"myPath";
                    [data writeToFile:filePath atomically:YES];
                }

            }


            dispatch_async(dispatch_get_main_queue(), ^(void) {

                [_hud hide:YES];

            });

        });


    }

Solution

  • Solved. I followed the implementation of HUD from this question: MBProgressHUD not showing

    Basically, I need to remove the HUD rather than simply hide it. Otherwise the HUD animation continued, invisible to me, hence causing the drop in frame rate.

    -(void)saveDataFile {
    
    
    // create HUD and add to view
        MBProgressHUD *hud = [[MBProgressHUD alloc]initWithView:self.parentView];
        hud.labelText = NSLocalizedString(@"Saving data...", nil);
        hud.delegate = self;
        [self.parentView addSubview:hud];
    
    
    // define block for saving data
    
            void (^saveData)() = ^() {
    
                @autoreleasepool {
    
                    id data = [self.model getData];
                    if (data != nil) {
    
                        NSString *filePath = @"myPath";
                        [data writeToFile:filePath atomically:YES];
                    }
    
                }
    
    }
    
    
    // use HUD convenience method to run block on a background thread
    [hud showAnimated:YES whileExecutingBlock:saveData];
    
    
        }
    
    
    // remove hud when done!
    //
    - (void)hudWasHidden:(MBProgressHUD *)hud {
    
        [hud removeFromSuperview];
    }