原理:
RunLoop在循環(huán)過(guò)程中監(jiān)聽(tīng)著port事件和timer事件,
當(dāng)前線(xiàn)程有任務(wù)時(shí)怖辆,喚醒當(dāng)當(dāng)線(xiàn)程去執(zhí)行任務(wù)掌测,
任務(wù)執(zhí)行完成以后,使當(dāng)前線(xiàn)程進(jìn)入休眠狀態(tài)。
代碼:.h
//
// LWQ_RunloopTableView.h
// BathoathProject
//
// Created by 葫蘆娃 on 2021/6/17.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^LoadOtherBlock)(id arguments);
@interface LWQ_RunloopTableView : UIViewController
//task模式優(yōu)化列表
@property(nonatomic, strong) NSMutableArray *taskArray;
@property(nonatomic, assign) NSInteger maxTaskNumber;
@property(nonatomic, strong) NSTimer *timer;
@property(nonatomic, strong) UITableView *tableView;
@property(nonatomic, copy)LoadOtherBlock mainBlock;
- (void)addTask;
@end
NS_ASSUME_NONNULL_END
.m
//
// LWQ_RunloopTableView.m
// BathoathProject
//
// Created by 葫蘆娃 on 2021/6/17.
//
#import "LWQ_RunloopTableView.h"
@interface LWQ_RunloopTableView ()<UITableViewDelegate,UITableViewDataSource>
@end
@implementation LWQ_RunloopTableView
- (void)viewDidLoad {
[super viewDidLoad];
//最大任務(wù)數(shù)
self.maxTaskNumber=10;
self.taskArray=[NSMutableArray new];
//定時(shí)器不斷循環(huán)task
self.timer = [NSTimer scheduledTimerWithTimeInterval:0.01 repeats:YES block:^(NSTimer * _Nonnull timer) {
NSLog(@"timer");
void(^task)() = [self.taskArray firstObject];
if (task) {
task();
}
[self.taskArray removeObject:task];
}];
}
//RuntLoop列表優(yōu)化
- (UITableView *)tableView{
if (!_tableView) {
_tableView=[[UITableView alloc]initWithFrame:CGRectMake(0, 0, KscreenWidth, KscreenHeight) style:UITableViewStylePlain];
_tableView.delegate=self;
_tableView.dataSource=self;
_tableView.backgroundColor=[UIColor whiteColor];
_tableView.estimatedRowHeight=100;
}
return _tableView;
}
- (void)addTask{
void(^task)(void) =^{
self.mainBlock(@"");
};
//添加任務(wù)
[self.taskArray addObject:task];
//超過(guò)任務(wù)數(shù)則刪除任務(wù)
if (self.taskArray.count == self.maxTaskNumber) {
[self.taskArray removeObjectAtIndex:0];
}
}
@end
//使用
繼承于LWQ_RunloopTableView創(chuàng)建controller
在
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
里調(diào)用[self addTask];
調(diào)用Block
self.mainBlock = ^(id _Nonnull arguments) {
//你自己的cell賦值等處理
};
//例如
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
LWQ_TableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:@"LWQ_TableViewCell" forIndexPath:indexPath];
if (!cell) {
cell=[[LWQ_TableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"LWQ_TableViewCell"];
}
[self addTask];
self.mainBlock = ^(id _Nonnull arguments) {
//你自己的代碼
cell.mainImageView.image = [UIImage imageWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"name" ofType:@"gif"]];
};
return cell;
}