一.使用NSPort进行线程间的通讯(端口和套接字来实现线程间通讯)
NSPort
对象必须添加到要接收消息的线程的Runloop
中- 接收消息的对象实现
NSPortDelegate
协议的-handlePortMessage:
方法来获取消息内容
代码中首先将self.mainPort
添加到主线程的Runloop
中,然后起新线程下载头像,下载完成后通过mainPort
发送消息,此时并没有手动切换线程,但是controller
中的回调却是在主线程中的,如此便完成了线程间的通讯。
self.mainPort = [[NSMachPort alloc]init];
// self.mainPort.delegate = self;
NSMutableArray *components = @[data].mutableCopy;
[self.port sendBeforeDate:[NSDate date] msgid:1 components:components from:self.downloaderPort reserved:0];
//代理方法
-(void)handlePortMessage:(NSPortMessage *)message{
NSLog(@"handlePortMessage: %@", [NSThread currentThread]);
NSArray *array = [(id)message valueForKey:@"components"];
NSD