iOS runloop代码详解2

本文通过一个iOS应用示例介绍了如何使用Swift处理触控事件,并展示了如何利用RunLoop进行循环处理直到满足特定条件。文章重点讲解了如何在主线程中正确地控制RunLoop的行为。

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


//
//  ViewController.m
//  test_runloop_03
//
//  Created by cdd on 16/8/2.
//  Copyright © 2016年 jeffasd. All rights reserved.
//

#import "ViewController.h"

#define TICK   NSDate *startTime = [NSDate date]
#define TOCK   NSLog(@"Time: %f", -[startTime timeIntervalSinceNow])

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    TICK;
    
    NSLog(@" get New 111");
    __block BOOL isGetNewUserSourceData = NO;
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        isGetNewUserSourceData = YES;
    });
    
//    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//        
//        
//        dispatch_sync(dispatch_get_main_queue(), ^{
//            
//            isGetNewUserSourceData = YES;
//        });
//        
//    });
    
    while (isGetNewUserSourceData == NO) {
        
//        NSLog(@"runloop is %@", [NSRunLoop currentRunLoop]);
        
        static int i = 0;
        i++;
        NSLog(@"i is %d", i);
        
        //手动修改主线程的运行模式可能导致主线程的 所用事件都是激活状态 导致其进入死循环状态
//        [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
//        [[NSRunLoop mainRunLoop] runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]];
//        [[NSRunLoop currentRunLoop] runMode:NSRunLoopCommonModes beforeDate:[NSDate distantFuture]];
        //主线程最好不要修改runloop的运行模式 主线程的运行模式让主线程自己切换
        [[NSRunLoop currentRunLoop] runUntilDate:[NSDate distantPast]];
    }
    
    TOCK;
    NSLog(@" get New ");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值