GCD,NSTimer等一些发现

第一次学习:

{

   NSMutableArr *mutableArr;
}

- (void)viewDidload {

     mutableArr =[ [NSMutableArray alloc] init];

       for (int i =0; i<100; i++) {

            [mutableArraddObject:[NSStringstringWithFormat:@"%d",i]];

       }

      dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0), ^{

          NSTimer *timer = [NSTimerscheduledTimerWithTimeInterval:3target:selfselector:@selector(methodOne)userInfo:nilrepeats:YES];

            [[NSRunLoopmainRunLoop]addTimer:timerforMode:NSDefaultRunLoopMode];

            [selfmethodTwo];   

        });
}

- (void)methodOne {
     [mutableArrremoveLastObject];
}

- (void)methodTwo {

    NSLog(@"%@",mutableArr);
}

 

试验发现methodOne不执行,而methodTwo是执行的,但是如果我们将上面红色字体涉及到的全局队列换成主线程

dispatch_get_main_queue(),那么下面两个方法都试是执行的.

答案是:nstimer只有在主线程才会自动添加到runloop里面去,在其他线程需要主动添加

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIGRITY_DEFAULT,0),^{

 NSTimer *timer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector(methodOne) userInfo:nil repeats:YES];

[self  methodTwo]; 

         [NSRunloop currentRunloop] addTimer:timer Mode:NSDefaultRunloopMode];

          [ [NSRunloop currentRunloop] run];

切忌,这里我们不能将currentRunloop改成mainRunLoop

这两句代码就是主动将timer添加到runloop

})

如果将[self methodTwo]; 写在 [ [NSRunloop currentRunloop] run]后面,methodTwo也不会走的。

第二次学习:

NSOperationQueue *testQueue = [[NSOperationQueue alloc] init];

    NSBlockOperation *operation1 = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"print 1”);

    }];

    NSBlockOperation *operation2 = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"print 2”);

    }];

    NSBlockOperation *operation3 = [NSBlockOperation blockOperationWithBlock:^{

        NSLog(@"print 3”);

    }];

    [operation1 addDependency:operation2];

    [operation2 addDependency:operation3];

    [testQueue addOperation:operation1];

    [testQueue addOperation:operation2];

    [testQueue addOperation:operation3];

打印结果是3,2,1   要注意哦。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值