我正在尝试学习GCD,所以我还没有完全掌握它是如何工作的。由于某种原因,在调用以下方法后,我经历了帧率的永久下降。如果我不使用分派函数,而只是在主循环中写入数据,那么帧率将保持在60。我不知道为什么。
-(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];
});
});
}
解决。我从这个问题开始跟踪HUD的实现:MBProgressHUD不显示
基本上,我需要删除HUD而不是简单地隐藏它。否则HUD动画继续,我看不见,因此导致帧率下降。
-(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];
}