三、RunLoop的应用
1.给子线程添加RunLoop
在正常情况下、子线程在执行完selector方法后就会被释放,如果需要从主线程中回到子线程就需要给子线程添加RunLoop
#import <Foundation/Foundation.h>
@interface ZLYThread : NSThread
@end
#import "ZLYThread.h"
@implementation ZLYThread
-(void)dealloc
{
NSLog(@"子线程被释放了");
}
@end
#import "ViewController.h"
#import "ZLYThread.h"
@interface ViewController ()
@property(nonatomic,strong) UIImageView * imageView;
@end
<pre name="code" class="objc">#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
@implementation ViewController- (void)viewDidLoad { [super viewDidLoad]; ZLYThread * thread = [[ZLYThread alloc] initWithTarget:self selector:@selector(showThread) object:nil]; [thread start]; }-(void)showThread{ NSLog(@"子线程执行完了");}
2016-09-03 15:56:25.070 Demo[4358:527692] 子线程执行完了
2016-09-03 15:56:25.071 Demo[4358:527692] 子线程被释放了
根据打印结果可以看出,在子线程执行完成后,子线程就被释放了
2.在子线程中添加RunLoop后就可以从主线程回到子线程,ViewController里面的代码如下
#import "ViewController.h"
#import "ZLYThread.h"
@interface ViewController ()
/****定时器(这里不用带*,因为dispatch_source_t就是个类,内部已经包含了*)*****/
@property(nonatomic,strong) dispatch_source_t timer;
@property(nonatomic,strong) UIImageView * imageView;
@property(nonatomic,strong) ZLYThread * thread;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
ZLYThread * thread = [[ZLYThread alloc] initWithTarget:self selector:@selector(showThread) object:nil];
self.thread = thread;
[thread start];
UIButton * button = [UIButton buttonWithType:UIButtonTypeCustom];
button.frame = CGRectMake(50, 100, 200, 50);
[button addTarget:self action:@selector(buttonClick:) forControlEvents:UIControlEventTouchUpInside];
[button setTitle:@"主线程切换到子线程" forState:UIControlStateNormal];
[button setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
[self.view addSubview:button];
}
-(void)buttonClick:(UIButton *)button
{
[self performSelector:@selector(backSubThread) onThread:self.thread withObject:nil waitUntilDone:YES];
NSLog(@"按钮点击事件执行完毕后才切换到子线程");
}
-(void)backSubThread
{
NSLog(@"当前线程%@",[NSThread currentThread]);
}
-(void)showThread
{
NSLog(@"子线程执行完了");
/*
【注】1.子线程的runloop需要自己动手创建,手动开启
2.子线程的runloop里面至少要有一个source或是timer
*/
[[NSRunLoop currentRunLoop] addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];
}
打印结果如下
2016-09-03 16:30:23.844 Demo[4714:590326] 子线程执行完了
2016-09-03 16:30:28.024 Demo[4714:590326] 当前线程<ZLYThread: 0x7fae825bb8d0>{number = 2, name = (null)}
2016-09-03 16:30:28.025 Demo[4714:590188] 按钮点击事件执行完毕后才切换到子线程
【注意】在
[
self
performSelector
:
@selector
(backSubThread)
onThread
:
self
.
thread
withObject
:
nil
waitUntilDone
:
YES
];方法中第四个参数为NO时 是等按钮点击事件执行完毕时,再执行子线程。
3.自动释放池创建和释放的时间
第一次创建时间为进入RunLoop的时候,
最后一次释放时间为RunLoop退出的时候
当RunLoop将要睡觉的时候会释放,然后创建一个新的自动释放池准备下一次循环