前言
聊天列表的刷新,消息收取的处理,都是大量数据的本地或者内存的处理.都可以考虑用dispatch_source_t来优化性能.
- 当同一时间,一个事件的的触发频率很高,那么Dispatch Source会将这些响应以ADD的方式进行累积,然后等系统空闲时最终处理,如果触发频率比较零散,那么Dispatch Source会将这些事件分别响应。
@implementation YHRefreshViewController {
dispatch_source_t _eventUnion;
}
- (void)viewDidLoad {
[super viewDidLoad];
_eventUnion = dispatch_source_create(DISPATCH_SOURCE_TYPE_DATA_ADD, 0, 0, dispatch_get_main_queue());
dispatch_source_set_event_handler(_eventUnion, ^{
NSLog(@"event Union"); //执行
});
dispatch_resume(_eventUnion);
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
for (int i = 0; i < 10; i++) {
dispatch_source_merge_data(_eventUnion, 1);
}
}
@end
- 上面代码只会打印一次
+下面我们来看下DISPATCH_SOURCE_TYPE_DATA_ADD
的所有类型
dispatch_source_merge_data()触发
1.
/*!
* @const DISPATCH_SOURCE_TYPE_DATA_ADD
* @discussion A dispatch source that coalesces data obtained via calls to
* dispatch_source_merge_data(). An ADD is used to coalesce the data.
*/
#define DISPATCH_SOURCE_TYPE_DATA_ADD
联合频率比较高的事件,传递数据会相加
2.
/*!
* @const DISPATCH_SOURCE_TYPE_DATA_OR
* @discussion A dispatch source that coalesces data obtained via calls to
* dispatch_source_merge_data(). A bitwise OR is used to coalesce the data.
*/
#define DISPATCH_SOURCE_TYPE_DATA_OR
联合频率比较高的事件,传递数据会按位或
3.
/*!
* @const DISPATCH_SOURCE_TYPE_WRITE
* @discussion A dispatch source that monitors a file descriptor for available
* buffer space to write bytes.
*/
#define DISPATCH_SOURCE_TYPE_WRITE
可以作为定时器,需要dispatch_source_set_timer();