利用Runloop优化流畅度

本文介绍了如何利用Runloop的观察者机制,在状态为kCFRunLoopExit和kCFRunLoopBeforeWaiting时执行耗时操作,以提高界面滑动时的流畅度。特别适用于不急需显示内容的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

利用Runloop优化流畅度

我们可以对runloop添加观察者,当观察到状态为kCFRunLoopExit,kCFRunLoopBeforeWaiting的时候,做一些耗时的处理,废话不说,直接上代码

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor redColor];

    UITableView *tableView = [[UITableView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:tableView];
    tableView.delegate = self;
    tableView.dataSource = self;

//    for (int i = 0; i < 100000; i ++){
//        UIView *view = [UIView new];
//        [self.view addSubview:view];
//    }

    __block NSMutableArray *arr = [[NSMutableArray alloc] init];
    for (int i = 0; i < 10000; i ++){
        [arr addObject:@0];
    }
    NSLog(@"添加完了");
    _arr = arr;

    _observer = CFRunLoopObserverCreateWithHandler(CFAllocatorGetDefault(), kCFRunLoopAllActivities, YES, 0, ^(CFRunLoopObserverRef observer, CFRunLoopActivity activity) {
        NSLog(@"----监听到RunLoop状态发生改变---%zd", activity);

        if ((activity == kCFRunLoopExit || activity == kCFRunLoopBeforeWaiting )  && arr.count > 0){

                UIView *view = [UIView new];
                [self.view addSubview:view];
                [arr removeObjectAtIndex:0];
                NSLog(@"还有%ld",arr.count);


            CFRunLoopWakeUp(CFRunLoopGetCurrent());
        }

    });
    CFRunLoopAddObserver(CFRunLoopGetCurrent(), _observer, kCFRunLoopDefaultMode);


    CFRelease(_observer);
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1000;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"123"];
    if (!cell){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"123"];
    }
    cell.backgroundColor = [UIColor colorWithRed:arc4random_uniform(256)/255.0 green:arc4random_uniform(256)/255.0 blue:arc4random_uniform(256)/255.0 alpha:1.0];

    return cell;
}
- (void)dealloc {
    CFRunLoopRemoveObserver(CFRunLoopGetCurrent(), _observer, kCFRunLoopCommonModes);
}

这里tableView滑动的时候是不会创建view的,只有滑动结束的时候才会继续创建,这主要用在不是很着急使用的场景对流畅度进行一定的优化

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值