1. 消息循环概念
RunLoop就是消息循环,每一个线程内部都有一个消息循环。
只有主线程的消息循环默认开启,子线程的消息循环默认不开启。
2. 子线程开启消息循环的3种方式:
(1)开启消息循环 使用run方法后无法停止消息循环。
[[
NSRunLoop
currentRunLoop
]
run
];
(2)指定循环运行时间
[[
NSRunLoop
currentRunLoop
]
runUntilDate
:[
NSDate
dateWithTimeIntervalSinceNow
:2]];
(3)apple推荐的方式(了解)
BOOL shouldKeepRunning
=
YES
;
// global
设置为global变量,可控制该消息循环的开闭;
NSRunLoop
*theRL = [
NSRunLoop
currentRunLoop
];
while (shouldKeepRunning && [theRL runMode:NSDefaultRunLoopMode beforeDate:[NSDate distantFuture]]);
3. RunLoop的目的:
a. 保证程序不退出 ;
b. 负责处理输入事件;
c. 如果没有事件发生,会让程序进入休眠状态。
4. 2种事件类型:
Input Sources (输入源) 和 Timer Sources (定时源)
输入源可以是键盘鼠标,NSPort, NSConnection 等对象;
定时源是NSTimer 事件。
5. 消息循环的使用:
(1)创建消息(即输入源);
(2)指定该事件(源)在循环中运行的模式,并加入循环;
(3)当事件的模式与消息循环的模式匹配的时候,消息才会运行。
6. 循环常用模式:
(1) NSDefaultRunLoopMode—默认模式(最常用的循环模式)
The mode to deal with input sources other than NSConnection objects. This is the most commonly used run-loop mode. Available in iOS 2.0 and later.
(2) NSRunLoopCommonModes—普通模式(一组模式的集合)
Objects added to a run loop using this value as the mode are monitored by all run loop modes that have been declared as a member of the set of “common" modes; see the description of CFRunLoopAddCommonMode for details.
7. 2个Demo
例子1:主线程的消息循环
/**
创建Timer
参数
1:
间隔时间 1s
参数
2:
对象 self
参数
3:
方法 task
参数
4:
自定义信息
参数5:是否重复执行 YES
*/
NSTimer
*timer = [
NSTimer
timerWithTimeInterval
:1
target
:
self
selector
:
@selector
(task)
userInfo
:
nil
repeats
:
YES
];
/**
把定时源加入到当前线程下的消息循环中
参数
1:
定时源
参数2:模式
*/
[[
NSRunLoop
currentRunLoop
]
addTimer
:timer
forMode
:
NSRunLoopCommonModes
];
-(
void
)task{
// 输出当前循环的模式
// 输出当前循环的模式
NSLog(@"%@",[NSRunLoop currentRunLoop].currentMode);
}
/**
事件在消息循环中的运行原理:
事件(即定时源Timer)模式有两种:
NSDefaultRunLoopMode(默认模式),
NSRunLoopCommonModes
;
主线程消息循环模式也有两种:
kCFRunLoopDefaultMode(默认模式),
kCFRunLoopDefaultMode。
当事件模式与消息循环模式相匹配的时候,消息才会运行。
现象:
当设置事件模式为NSDefaultRunLoopMode 时,
拖动UITextView界面
,
定时源停止运行;当停止拖动,定时源又继续运行;
当设置事件模式为
NSRunLoopCommonModes 时,
拖动UITextView界面
,
定时源持续运行不受影响。
此外,当
设置事件模式为
NSRunLoopCommonModes 时,
未拖动
UITextView界面时,消息循环的模式为
kCFRunLoopDefaultMode ;
当拖动
UITextView界面时,消息循环的模式自动变为
UITrackingRunLoopMode 。
*/
例子2:子线程的消息循环
//
创建子线程
NSThread *thread = [[ NSThread alloc ] initWithTarget : self selector : @selector (task2) object : nil ];
NSThread *thread = [[ NSThread alloc ] initWithTarget : self selector : @selector (task2) object : nil ];
[thread start];
/**
往指定线程的消息循环中加入源
参数
1:
方法
参数
2:
指定线程
参数
3:
对象
参数
4:
等待方法执行完成
*/
[self performSelector:@selector(addtask) onThread:thread withObject:nil waitUntilDone:NO];
-(
void
)task2{
[[
NSRunLoop
currentRunLoop
]
runUntilDate
:[
NSDate
dateWithTimeIntervalSinceNow
:5]];
}
-(
void
)addtask{
NSLog ( @"addtask is running" );
NSLog ( @"addtask is running" );
}
8. 自动释放池是什么时候创建的?又是什么时候销毁的?
答:
每一次消息循环开始的时候会先创建自动释放池,运行循环结束前,会释放自动释放池。
自动释放池被销毁或耗尽时,会向池中所有对象发送 release 消息,释放所有 autorelease 的对象。
注意:使用 NSThread 做多线程开发时,需要在线程调度方法中手动添加自动释放池。