ios之runloop笔记

网上关于runloop的文章不计其数,再此,贴个自认为讲的比较简单明了的文章

 

个人理解:

ios的runloop应该是类似于线程之间的消息监听+队列(队列于外部不透明,支持多重send消息模式,perform selector,timer,UI事件等等)
和android的Looper非常相似,和windows的消息循环也很类似,具体底层实现不关注,直接贴测试代码

 

#import "ViewController.h"

@interface ViewController ()

@property(nonatomic, strong) NSThread *thread;
@property(nonatomic, strong) NSThread *msgThread;

@end

@implementation ViewController

- (void) viewDidLoad{
    [super viewDidLoad];
    
    [self initMsgThread];
}

- (void) initMsgThread{
    
    self.msgThread = [[NSThread alloc]initWithTarget:self selector:@selector(msgThreadInitFunc) object:nil];
    [self.msgThread start];
}

- (void) msgThreadInitFunc{
    NSLog(@"msgThreadInitFunc run, %@",[NSThread currentThread]);
    
    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    
    NSLog(@"msgThreadInitFunc run");
    
}

//******************************************************************************************************************
- (void) postMsgToThread{
    [[[NSThread alloc]initWithTarget:self selector:@selector(asyncPostMsgToThread) object:nil] start];
}

- (void) asyncPostMsgToThread{
    [self performSelector:@selector(onThreadMsgProc) onThread:self.msgThread withObject:nil waitUntilDone:NO];
}

- (void) onThreadMsgProc{
    NSLog(@"do some work %@, %s", [NSThread currentThread], __FUNCTION__);
}

//******************************************************************************************************************
- (void) startTimerOnThread{
    self.thread = [[NSThread alloc]initWithTarget:self selector:@selector(asyncStartTimerOnThread) object:nil];
    [self.thread start];
}

- (void) asyncStartTimerOnThread{
    [self performSelector:@selector(asyncStartTimer) onThread:self.thread withObject:nil waitUntilDone:NO];
    
//    [[NSRunLoop currentRunLoop] addPort:[[NSPort alloc] init] forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
}

- (void) asyncStartTimer{
    [NSTimer scheduledTimerWithTimeInterval:3.0 target:self selector:@selector(timerFired:)userInfo:nil repeats:YES];
}

- (void) timerFired:(id)timer{
    NSLog(@"on thread timer %s",__FUNCTION__);
}

//******************************************************************************************************************
- (IBAction)testButtonTapped:(id)sender {
//    [self postMsgToThread];
    [self startTimerOnThread];
}

@end

当然用block也是一样的,子线程必须创建runloop来监听消息,否则这个子线程是无法处理类似performSelector,NSTimer之类的消息的

线程之间通信,cocos2dx,u3d,ios,android,win32,都是基于消息队列的模式,一个发,一个收,写时加锁,别无更好的办法了

转载于:https://www.cnblogs.com/ziyouchutuwenwu/p/3180904.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值