Cocoa provides 2 ways to communicate between iOS threads, 1 is performselector, and the other 1 is port.
First of all, the 1th kind, performselector, has the following several:
The 2nd type is the Nsmachport way. Nsport has 3 subclasses, Nssocketport, Nsmessageport, Nsmachport, but only nsmachport available under iOS.
By registering nsmachport in the receive thread, using this port in another thread to send a message, the registered thread receives the message, and then eventually calls a callback function in the main thread.
As you can see, the result of using Nsmachport is 1 functions that call other threads, and that's exactly what Performselector does, so Nsmachport is a chicken. Inter-thread communication should be done through performselector.
The performance of inter-thread communication:
1 Threads pass data to another 1 threads
After performing a specific task in 1 threads, go to another 1 thread to continue the task
Here is an example of downloading a picture:
| 12345678910111213141516171819202122232425262728293031323334 |
@interface BTThreadViewController (){ UIImageView *imagev;}@end- (void)viewDidLoad{ [super viewDidLoad]; imagev = [[UIImageView alloc] initWithFrame:CGRectMake(100, 100, 100, 100)]; [self.view addSubview:imagev]; //子线程里面调用downImage方法下载图片 [self performSelectorInBackground:@selector(downImage) withObject:nil];}-(void)downImage{ //从网络中下载图片 NSURL *url = [NSURL URLWithString:@"http://i8.topit.me/8/c1/31/1142319854bdc31c18o.jpg"]; //将图片转换为二进制数据 NSData *imgData = [NSData dataWithContentsOfURL:url]; //数据转换成图片 UIImage *img = [UIImage imageWithData:imgData]; //回到主线程设置图片 [self performSelectorOnMainThread:@selector(senderImage:) withObject:img waitUntilDone:NO];}-(void)senderImage:(UIImage *)image{ imagev.image = image;}
|
iOS Development multithreading-Inter-thread communication