//献上 刷新UI耗时解决方案
//你的所有异步操作 是否操作UI时是否都会回到主线程??
//iOS 你怎么了 开发者的生态圈怎么了 哎~ 心情不好!
typedef BOOL(^RunLoopBlock)(void);
@interface ViewController ()
//定时器
@property(nonatomic,strong) NSTimer *timer;
//任务数组
@property(nonatomic,strong) NSMutableArray *tasks;
//最大任务数
@property(nonatomic,assign) NSInteger maxQueueLength;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
_tasks = [NSMutableArray array];
_maxQueueLength = 18;
_timer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(timerMothod) userInfo:nil repeats:YES];
[self addRunLoopObserver];
}
- (void)timerMothod {
}
+ (void)zhaodacai {
NSLog(@"zhadaocai");
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
[self addTask:^BOOL{
[ViewController zhaodacai];
return YES;
}];
}
- (void) addTask:(RunLoopBlock)unit {
[self.tasks addObject:unit];
if (_tasks.count > _maxQueueLength) {
[self.tasks removeObjectAtIndex:0];
}
}
static void CallBack (CFRunLoopObserverRef observer, CFRunLoopActivity activity, void *info){
ViewController *vc = (__bridge ViewController *)(info);
if (vc.tasks.count == 0 ) {
return;
}
BOOL result = NO;
while (result == NO && vc.tasks.count) {
RunLoopBlock unit = vc.tasks.firstObject;
unit();
[vc.tasks removeObjectAtIndex:0];
}
}
//添加观察者
- (void)addRunLoopObserver {
CFRunLoopRef runloop = CFRunLoopGetCurrent();
CFRunLoopObserverContext context = {
0,
(__bridge void *)(self),
&CFRetain,
&CFRelease,
NULL
};
CFRunLoopObserverRef defaultModelObserver;
defaultModelObserver = CFRunLoopObserverCreate(NULL, kCFRunLoopBeforeWaiting, YES, NSIntegerMax - 99, &CallBack, &context);
CFRunLoopAddObserver(runloop, defaultModelObserver, kCFRunLoopDefaultMode);
//c语言必须释放
CFRelease(defaultModelObserver);
}