异步处理3:使用nslock锁定线程
锁定线程:确保两个线程(处理的程序)不会使用同一段代码
1.添加一个属性:@property(nonatomic,strong)NSLock*threadLock;
2.viewDidLoad中新建对象NSLock,self.threadLock=[NSLock alloc]init];
3.在适当的位置添加锁[self.threadLock lock];
4.适当的位置:
-(void)bigTask{
** [self.threadLock lock];**
@autoreleasepool {
int updateUIWhen = 500;
for (int i=0; i<10000; i++) {
NSString*newString=[NSString stringWithFormat:@"i=%d",i];
NSLog(@"%@ ",newString);
if (i==updateUIWhen) {
float f=(float)i/10000;
NSNumber*percentDone=[NSNumber numberWithFloat:f];
[self performSelectorOnMainThread:@selector(updateProgressViewWithPercentage:)withObject:percentDone waitUntilDone:YES];
updateUIWhen=updateUIWhen+1000;
}
}
[self performSelectorOnMainThread:@selector(updateProgressViewWithPercentage:)withObject:[NSNumber numberWithFloat:1.0] waitUntilDone:YES];
[self.myActivityIndicator stopAnimating];
}
** [self.threadLock unlock];**
}
打 ** 的地方就是 加锁的地方
结果: 程序运行点击一次,会扥到for循环 也就是进度条执行完成后才会执行下一次的运行