異步處理3:使用nslock鎖定線程
鎖定線程:確保兩個線程(處理的程序)不會使用同一段代碼
1.添加一個屬性:@property(nonatomic,strong)NSLock*threadLock;
2.viewDidLoad中新建對象NSLock,self.threadLock=[NSLock alloc]init];
3.在適當?shù)奈恢锰砑渔i[self.threadLock lock];
4.適當?shù)奈恢?
-(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循環(huán) 也就是進度條執(zhí)行完成后才會執(zhí)行下一次的運行