iOS 指定事件回调线程

  • NSUrlSessionExtension.h
@protocol NSUrlSessionExtensionDelegate 

- (void)callBackHandle;

@end

@interface NSUrlSessionExtension : NSObject

- (instancetype)initUrlSessionWithDelegate:(id)delegate backQueue:(NSOperationQueue *)queue;
@property (nonatomic, assign)  id   delegate;


@end
  • NSUrlSessionExtension.m
@interface NSUrlSessionExtension()

@property (nonatomic, strong)  NSOperationQueue           *queue;


@end

@implementation NSUrlSessionExtension

- (instancetype)initUrlSessionWithDelegate:(id)delegate backQueue:(NSOperationQueue *)queue{
    if(self = [super init]) {
        
        _queue = queue;
        _delegate = delegate;
        [self back];

    }
    return self;
}

- (void)back{
    
   NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
       if (self.delegate && [self.delegate respondsToSelector:@selector(callBackHandle)]) {
           [self.delegate callBackHandle];
       }
       NSLog(@"Task1 当前线程%@", [NSThread currentThread]);
       NSLog(@"Task1 当前队列%@", [NSOperationQueue currentQueue]);
   }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self.queue addOperation:operation];
    });
}

@end

  • ViewController.m

- (void)viewDidLoad {
    [super viewDidLoad];

    NSOperationQueue *queue = [[NSOperationQueue alloc]init];
    queue.name = @"ghq";
    queue.maxConcurrentOperationCount = 1;
    _extension = [[NSUrlSessionExtension alloc] initUrlSessionWithDelegate:self backQueue:queue];
    
}

- (void)callBackHandle{
    NSLog(@"%@=======%@",[NSOperationQueue currentQueue],[NSOperationQueue currentQueue].name);
}

打印结果:

2020-07-17 16:08:55.695743+0800 dfadfasd[16835:274330] {name = 'ghq'}=======ghq
2020-07-17 16:08:56.330191+0800 dfadfasd[16835:274330] Task1 当前线程{number = 5, name = (null)}
2020-07-17 16:08:57.329107+0800 dfadfasd[16835:274330] Task1 当前队列{name = 'ghq'}

你可能感兴趣的:(iOS 指定事件回调线程)