RunLoop猶如其名循環。
RunLoop 中有多重模式。
在一個“時刻”只能值執行一種模式。
因此在使用RunLoop時要注意所實現的效果有可能不是你想要的。
在這裡用NSTimer展示一下Runloop的簡單實現。
在故事板中添加一個TextView(用於測試)

我們吧nstimer加入到NSDefaultRunLoopMode模式中

在上面我們可以很清晰的看到,當我們滾動TextView的時候,nstimer不在執行。
//
// ViewController.m
// CX RunLoop淺析
//
// Created by ma c on 16/3/29.
// Copyright © 2016年 xubaoaichiyu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSTimer * timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(test) userInfo:nil repeats:YES];
//添加到默認的runloop中
[[NSRunLoop mainRunLoop]addTimer:timer forMode:NSDefaultRunLoopMode];
[timer fire];
}
-(void)test{
NSLog(@"旭寶愛吃魚");
}
@end
我們吧nstimer加入到UITrackingRunLoopMode模式中

在上面我們可以很清晰的看到,當我們滾動TextView的時候,nstimer執行。
//
// ViewController.m
// CX RunLoop淺析
//
// Created by ma c on 16/3/29.
// Copyright © 2016年 xubaoaichiyu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSTimer * timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(test) userInfo:nil repeats:YES];
//添加到默認的runloop中
[[NSRunLoop currentRunLoop]addTimer:timer forMode:UITrackingRunLoopMode];
[timer fire];
}
-(void)test{
NSLog(@"旭寶愛吃魚");
}
@end
我們吧nstimer加入到NSRunLoopCommonModes模式中

在上面我們可以很清晰的看到,當我們滾動與不滾動TextView的時候,nstimer都執行。
//
// ViewController.m
// CX RunLoop淺析
//
// Created by ma c on 16/3/29.
// Copyright © 2016年 xubaoaichiyu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSTimer * timer = [NSTimer timerWithTimeInterval:3 target:self selector:@selector(test) userInfo:nil repeats:YES];
//添加到默認的runloop中
[[NSRunLoop currentRunLoop]addTimer:timer forMode:NSRunLoopCommonModes];
[timer fire];
}
-(void)test{
NSLog(@"旭寶愛吃魚");
}
@end
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(test) userInfo:nil repeats:YES];
自動添加到runloop 並且默認為NSDefaultRunLoopMode.
但是我們可以通過與上面相同的方法改變模式。

//
// ViewController.m
// CX RunLoop淺析
//
// Created by ma c on 16/3/29.
// Copyright © 2016年 xubaoaichiyu. All rights reserved.
//
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
}
-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
NSTimer * timer = [NSTimer scheduledTimerWithTimeInterval:2 target:self selector:@selector(test) userInfo:nil repeats:YES];
}
-(void)test{
NSLog(@"旭寶愛吃魚");
}
@end