第一次学习:
{
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 要注意哦。