/*
1.线程同步:原子操作,条件锁,递归锁,@synchronized。NSCondition:同步执行的顺序。
2.线程间通信:
在主线程做事:-performSelectorOnMainThread
在子线程做事:-performSelectorInBackground
在指定线程做事:-performSelector: onThread: withObject: waitUntilDone:
在当前线程做事:-performSelector: withObject:
取消发送给当前线程的某消息:+cancelPreviousPerformRequestsWithTarget: selector: object:
*/
对NSOperation继承实现,进行队列的操作。
官方实现:
NSBlockOperation
NSInvocationOperation
自定义实现:.h
#import <Foundation/Foundation.h>
typedef void (^CompletedBlock) (NSDictionary *dictionary);
@interface MyOperation : NSOperation
@property (nonatomic, strong) NSURL *imageUrl;
@property (nonatomic, strong) id target;
@property (nonatomic, strong) CompletedBlock completedBlock;
- (instancetype)initWithUrl:(NSURL*)imageUrl target:(id)target completedBlock:(CompletedBlock)completedBlock;
@end
.m
#import "MyOperation.h"
@implementation MyOperation
- (void)main {
NSData *data = [NSData dataWithContentsOfURL:self.imageUrl];
NSDictionary *dict = @{@"data":data};
self.completedBlock(dict);
}
- (instancetype)init{
return nil;
}
- (instancetype)initWithUrl:(NSURL*)imageUrl target:(id)target completedBlock:(CompletedBlock)completedBlock{
self = [super init];
if (self) {
_imageUrl = imageUrl;
_target = target;
_completedBlock = completedBlock;
}
return self;
}
@end
应用举例:
NSString *urlStr = @"http://b.hiphotos.baidu.com/image/pic/item/9e3df8dcd100baa1e477e5524310b912c9fc2efb.jpg";
MyOperation *opera = [[MyOperation alloc]initWithUrl:[NSURL URLWithString:urlStr] target:self completedBlock:^(NSDictionary *dictionary) {
UIImage *image = [UIImage imageWithData:dictionary[@"data"]];
UIImageView *imageView = [[UIImageView alloc]initWithFrame:CGRectMake(80, 290, 80, 120)];
imageView.image = image;
[self.view addSubview:imageView];//回调根据你加的queue,会在不同的线程执行。
NSThread *cu = [NSThread currentThread];
cu.name = @"current";
NSString *str = [NSThread mainThread].name;
NSLog(@"%@= %@", str, cu);
}];
// NSOperationQueue *myq = [[NSOperationQueue alloc]init];
// [myq addOperation:opera];//子线程执行completedBlock
[[NSOperationQueue mainQueue] addOperation:opera];//主线程执行completedBlock