首页 > 代码库 > iOS 如何启动和停止RunLoop
iOS 如何启动和停止RunLoop
#import "ViewController.h"
@interface ViewController ()<NSURLConnectionDataDelegate>
@property (nonatomic, assign) CFRunLoopRef runLoop;// 保持同一个线程 C语言
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
dispatch_async(dispatch_get_global_queue(0, 0), ^{
NSURLConnection *conn = [NSURLConnection connectionWithRequest:[NSURLRequest requestWithURL:@""] delegate:self];
//决定代理在哪个队列执行
[conn setDelegateQueue:[[NSOperationQueue alloc] init]];
// 放在子线程, 子线程的循环默认是不开器的,不汇时刻的监听返回的数据事件
// 因此要手动的启动 子线程
// [[NSRunLoop currentRunLoop] run];
self.runLoop = CFRunLoopGetCurrent();
CFRunLoopRun(); // 启动
});
}
#pragma mark-<NSURLConnectionDataDelegate>
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
// 关闭runloop
CFRunLoopStop(self.runLoop);// 关闭保持前后一致
}
@end
iOS 如何启动和停止RunLoop