美文网首页
iOS 指定事件回调线程

iOS 指定事件回调线程

作者: 年轻就要活出样 | 来源:发表于2020-07-17 16:09 被阅读0次
  • NSUrlSessionExtension.h
@protocol NSUrlSessionExtensionDelegate <NSObject>

- (void)callBackHandle;

@end

@interface NSUrlSessionExtension : NSObject

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


@end
  • NSUrlSessionExtension.m
@interface NSUrlSessionExtension()

@property (nonatomic, strong)  NSOperationQueue           *queue;


@end

@implementation NSUrlSessionExtension

- (instancetype)initUrlSessionWithDelegate:(id<NSUrlSessionExtensionDelegate>)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] <NSOperationQueue: 0x7f8053413550>{name = 'ghq'}=======ghq
2020-07-17 16:08:56.330191+0800 dfadfasd[16835:274330] Task1 当前线程<NSThread: 0x6000038b8080>{number = 5, name = (null)}
2020-07-17 16:08:57.329107+0800 dfadfasd[16835:274330] Task1 当前队列<NSOperationQueue: 0x7f8053413550>{name = 'ghq'}

相关文章

网友评论

      本文标题:iOS 指定事件回调线程

      本文链接:https://www.haomeiwen.com/subject/bhnghktx.html