IOS - RunLoop訊息迴圈

來源:互聯網
上載者:User

標籤:

什麼是RunLoop?

  -RunLoop就是訊息迴圈,每一個線程內部都有一個訊息迴圈。  -只有主線程的訊息迴圈預設開啟,子線程的訊息迴圈預設不開啟。   RunLoop的目的  -保證程式不退出 。  -負責處理輸入事件。    -如果沒有事件發生,會讓程式進入休眠狀態  。  事件類型Input Sources (輸入源) & Timer Sources (定時源)

  -輸入源可以是鍵盤滑鼠,NSPort, NSConnection 等對象,定時源是NSTimer 事件

      添加訊息到迴圈中

  -建立輸入源。(以NSTimer為例)

  -指定該事件(源)在迴圈中啟動並執行模式,並加入迴圈。

[self performSelector:@selector(demo2) onThread:thread withObject:nil waitUntilDone:NO];[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];

          

迴圈常用模式

  NSDefaultRunLoopMode--預設模式

  NSRunLoopCommonModes--普通模式

   

 

    //1.NSTimer定時源    NSTimer *timer = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(demo) userInfo:nil repeats:YES];    //2.把定時源加入到當前線程的訊息迴圈中    /*     1.定時源     2.模式      NSDefaultRunLoopMode 觸摸介面->timer停止->手放開->timer運行     NSRunLoopCommonModes 觸摸介面不受影響     觸摸介面kCFRunLoopDefaultMode->UITrackingRunLoopMode->手放開->kCFRunLoopDefaultMode     */    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];    //3.當訊息迴圈的模式和訊息的模式相匹配,訊息才能運行

總結

1.建立訊息

2.把訊息放入迴圈,並指定訊息啟動並執行模式

3.在與迴圈的模式比對的時候,訊息運行

 

子線程中的訊息迴圈

 //子線程的訊息迴圈    NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(demo) object:nil];    [thread start];    //輸入源    /*     1.方法     2.線程     3.參數     4.是否等待方法的完成     */    //建立輸入源,加入到子線程的訊息迴圈    //只有主線程的訊息迴圈預設開啟,子線程的訊息迴圈預設不開啟。->手動開啟子線程的訊息迴圈    [self performSelector:@selector(talk) onThread:thread withObject:nil waitUntilDone:NO];
-(void)demo{    NSLog(@"demo is running");//    NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);    //手動開啟子線程的訊息迴圈    //1.run方法開了關不了OC    [[NSRunLoop currentRunLoop] run];        //2.指定時間->不靠譜 不確定方法具體執行的時間長度等等因素//    [[NSRunLoop currentRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:1]];        //3.apple推薦(瞭解)//    BOOL shouldKeepRunning = YES;        // global//    NSRunLoop *theRL = [NSRunLoop currentRunLoop];//    while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);    NSLog(@"ok");

 

 

 

IOS - RunLoop訊息迴圈

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.