iOS的有三種多線程技術:
- (instancetype)initWithTarget:(id)target selector:(SEL)selector object:(nullableid)argument;
2)類方法
+ (void)detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(nullableid)argument;
- (void)viewDidLoad {
[super viewDidLoad];
NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(doSomething) object:nil];
[myThread start];
}
-(void)doSomething{
NSLog(@"新線程:%@",[NSThread currentThread]);
}
- (void)viewDidLoad {
[super viewDidLoad];
NSLog(@"主線程%@",[NSThread currentThread]);
[NSThread detachNewThreadSelector:@selector(doSomething) toTarget:self withObject:nil];
}
-(void)doSomething{
NSLog(@"新線程:%@",[NSThread currentThread]);
}
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@property (weak, nonatomic) IBOutlet UIImageView *myImageView;
@end
#import "ViewController.h"
#define imgUrl @"http://c.hiphotos.baidu.com/image/w%3D310/sign=4b3d50d58813632715edc432a18ea056/d52a2834349b033b015730d317ce36d3d439bdd8.jpg"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// NSThread *myThread = [[NSThread alloc]initWithTarget:self selector:@selector(downLoadImg) object:nil];
// [myThread start];
NSLog(@"主線程%@",[NSThread currentThread]);
[NSThread detachNewThreadSelector:@selector(downLoadImg) toTarget:self withObject:nil];
}
-(void)downLoadImg{
NSLog(@"新線程:%@",[NSThread currentThread]);
NSData *data = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:imgUrl]];
UIImage *image = [[UIImage alloc]initWithData:data];
if (image) {
//通知主線程更新UI
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
}
}
-(void)updateUI:(UIImage*)image{
self.myImageView.image = image;
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
}
其中,線程間的通訊:通知主線程更新UI
- (void)performSelectorOnMainThread:(SEL)aSelector withObject:(nullable id)arg waitUntilDone:(BOOL)wait;
除了更新主線程,也可以指定其他線程:- (void)performSelector:(SEL)aSelector onThread:(NSThread *)thr withObject:(nullable id)arg waitUntilDone:(BOOL)wait;