美文网首页
iOS多线程问题四丶NSOperation

iOS多线程问题四丶NSOperation

作者: Scheng_ | 来源:发表于2017-04-24 11:08 被阅读0次

    *由于GCD的线程开出去之后就没法管理,所以苹果又推出NSOperaton
    NSOperation和NSOperationQueue实现多线程
    1.先将需要执行的操作封装到一个NSOperation对象中
    2.然后将NSOperation对象添加到NSOperationQueue中
    3.系统会自动将NSOperation中封装的操作放到一条新线程中执行

    1.传值方法
    - (void)testInvocation {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    //NSOperationQueue *queue = [NSOperationQueue mainQueue];
    NSInvocationOperation *invocation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(task:) object:@"abc"];// [invocation start];
    [queue addOperation:invocation];}
    打印
    - (void)task:(NSString *)str {
    NSLog(@"%@--%@",str,[NSThread currentThread]);}
    2.1block块方法
    - (void)testBlockOperate {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    NSBlockOperation *block = [NSBlockOperation blockOperationWithBlock:^{
    NSLog(@"block task1 %@",[NSThread currentThread]);
    }];
    [block addExecutionBlock:^{
    NSLog(@"block task2 %@",[NSThread currentThread]);
    }];
    //[block start];
    [queue addOperation:block];}

    2.2
    - (void)addQueueBlock {
    NSOperationQueue *queue = [[NSOperationQueue alloc] init];
    [queue addOperationWithBlock:^{
    NSLog(@"task1 %@",[NSThread currentThread]);
    }];
    [queue addOperationWithBlock:^{
    NSLog(@"task2 %@",[NSThread currentThread]);
    }];}

    调用
    - (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    // [self testInvocation];
    // [self testBlockOperate];
    [self addQueueBlock];}

    相关文章

      网友评论

          本文标题:iOS多线程问题四丶NSOperation

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