Runloop的最简单使用
2017-02-22 15:56
204 查看
对于Runloop,写写自己的使用场景。比较详细、深入的讲解可以看这里这里,。
AFURLConnectionOperation 这个类是基于 NSURLConnection 构建的,其希望能在后台线程接收 Delegate 回调。为此 AFNetworking 单独创建了一个线程,并在这个线程中启动了一个 RunLoop:
RunLoop 启动前内部必须要有至少一个 Timer/Observer/Source,所以 AFNetworking 在 [runLoop run] 之前先创建了一个新的 NSMachPort 添加进去了。通常情况下,调用者需要持有这个 NSMachPort (mach_port) 并在外部线程通过这个 port 发送消息到 loop 内;但此处添加 port 只是为了让 RunLoop 不至于退出,并没有用于实际的发送消息。
我的NSTimer与Runloop的第一次应用 O(∩_∩)O~
iOS这东西,越做越感觉自己菜鸡,需要深入学习的东西还有很多啊!
AFURLConnectionOperation 这个类是基于 NSURLConnection 构建的,其希望能在后台线程接收 Delegate 回调。为此 AFNetworking 单独创建了一个线程,并在这个线程中启动了一个 RunLoop:
+ (void)networkRequestThreadEntryPoint:(id)__unused object { @autoreleasepool { [[NSThread currentThread] setName:@"AFNetworking"]; NSRunLoop *runLoop = [NSRunLoop currentRunLoop]; [runLoop addPort:[NSMachPort port] forMode:NSDefaultRunLoopMode]; [runLoop run]; } } + (NSThread *)networkRequestThread { static NSThread *_networkRequestThread = nil; static dispatch_once_t oncePredicate; dispatch_once(&oncePredicate, ^{ _networkRequestThread = [[NSThread alloc] initWithTarget:self selector:@selector(networkRequestThreadEntryPoi 4000 nt:) object:nil]; [_networkRequestThread start]; }); return _networkRequestThread; }
RunLoop 启动前内部必须要有至少一个 Timer/Observer/Source,所以 AFNetworking 在 [runLoop run] 之前先创建了一个新的 NSMachPort 添加进去了。通常情况下,调用者需要持有这个 NSMachPort (mach_port) 并在外部线程通过这个 port 发送消息到 loop 内;但此处添加 port 只是为了让 RunLoop 不至于退出,并没有用于实际的发送消息。
- (void)start { [self.lock lock]; if ([self isCancelled]) { [self performSelector:@selector(cancelConnection) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } else if ([self isReady]) { self.state = AFOperationExecutingState; [self performSelector:@selector(operationDidStart) onThread:[[self class] networkRequestThread] withObject:nil waitUntilDone:NO modes:[self.runLoopModes allObjects]]; } [self.lock unlock]; }
我的NSTimer与Runloop的第一次应用 O(∩_∩)O~
if (!self.refreshQRCodeTimer) { self.refreshQRCodeTimer = [NSTimer scheduledTimerWithTimeInterval:60 target:self selector:@selector(requestUserSelfQRCodeStr) userInfo:nil repeats:YES]; [[NSRunLoop currentRunLoop] addTimer:self.refreshQRCodeTimer forMode:NSRunLoopCommonModes]; }
iOS这东西,越做越感觉自己菜鸡,需要深入学习的东西还有很多啊!
相关文章推荐
- RunLoop的一些简单使用
- jni得简单使用
- 在 VB 中简单使用 HTMLHELP (*.chm) 帮助
- 通过一个简单的SWING日历BEAN开发学习Calendar类的使用(2)JCalendar源代码
- SpringFramework中的AOP简单使用
- 对MSNP9协议的简单使用示例
- Win32汇编教程三 一个简单的对话框 --- 兼谈资源文件的使用
- python中使用状态机的简单例子---截取'/x00'之前的字符串
- 使用C#开发一个简单的P2P应用
- 使用Java实现对dbf文件的简单读写
- PHP面向对象的使用教程 简单数据库连接
- 在ASP中使用简单Java类
- 简单使用Delphi中的TO-DO List
- 通过一个简单的SWING日历BEAN开发学习Calendar类的使用(1)Calendar概述
- 使用timer控件创建一个简单的报警程序
- 不使用ATL向导,创建一个简单的ATL对话框程序.
- 使用Delphi,SDK编写Windows简单程序
- 使用C# Builder建一个简单的ASP.NET应用程序
- 使用自定义的WebControl来构建简单的WebForm
- 了解POP3协议,使用简单的代码监控pop3邮箱,或者不用代码,直接使用telnet