Runloop 与 NSTimer
一、Runloop
1、作用
1.保持程序运行
2.处理app的各种事件(比如触摸,定时器等等)
3.节省CPU资源,提高性能。
2、RunLoop与线程
1.每条线程都有唯一的与之对应的RunLoop对象。
2.主线程的RunLoop已经创建好了,而子线程的需要手动创建。
3、a profound comprehension
一个线程一次只能执行一个任务,执行完成后线程就会退出。如果我们需要一个机制,让线程能随时处理事件但并不退出.
RunLoop模型的关键点在于:如何管理事件/消息,如何让线程在没有处理消息时休眠以避免资源占用、在有消息到来时立刻被唤醒。
4、a convinving instance
int main(int argc, char * argv[]) {
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
如果修改成
int main(int argc, char * argv[]) {
@autoreleasepool {
int res = UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
NSLog(@"hello");
return res;
}
}
运行的结果永远无法输出hello, 这就说明了程序一直在运行着。其实这都是RunLoop的功劳,它的其中一个功能就是保持程序的持续运行。
实际的效果如下:
BOOL running = YES;
do {
// 执行各种操作
} while (running);
return 0;
RunLoop 就是这样一个函数,其内部是一个 do-while 循环。
程序一直在while()里运行着,其实是一个死循环。
在UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]))这个函数的内部就已经启动了一个RunLoop,所以函数一直没有返回,这才使得程序保持运行。
这个默认启动的RunLoop是和主线程相关的!!!
二、关于NSTimer
1、function
1)在指定的时间执行指定的任务
2)每隔一段时间执行指定的任务
2、NSTimer与Runloop
可以把运行循环理解成一个系统级的线程,它时刻在监听着系统各种事件,一旦有事件发生,他就会触发处于运行循环中的程序。NSTimer也一样,只有加入运行循环中才能正常运行。
3、usage: scheduledTimerWith
开启一个定时任务:
[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
每间隔2.0秒
调用self(一般都填self)里的@selector方法,
nil: 传递信息(可以以字典的形式,将信息传递给要执行的方法
Yes:是否重复执行,如果NO,timer执行一次后便失效
Keynote:scheduledTimerWithTimeInterval方法创建完timer之后,会自动以NSDefaultRunLoopModel模式加入运行循环。
4、usage:timerWith
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
但是timerWithTimeInterval需要加入:
NSTimer *timer = [NSTimer timerWithTimeInterval:1.0 target:self selector:@selector(timerTest) userInfo:nil repeats:YES];
//需要加入这一句
[[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
repeat Keynote:scheduledTimerWithTimeInterval方法创建完timer之后,会自动以NSDefaultRunLoopModel模式加入运行循环。