在實際開發中,經常需要異步處理數據,然后刷新UI只能在主線程,以下是幾種主線程操作的方法,gcd方法是大家最熟悉的。
1. GCD方法(最常見,使用簡單方便,蘋果封裝)
dispatch_async(dispatch_get_main_queue(), ^{
? ? ?//do something
});
2.NSOperation方法
NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];主隊列
NSBlockOperation *operation = [NSBlockOperation blockOperationWithBlock:^{
//do something
}];
[mainQueue addOperation:operation];//不要忘記加這句
3. NSThread方法
[selfperformSelector:@selector(method) onThread:[NSThread mainThread] withObject:nilwaitUntilDone:YESmodes:nil];
[selfperformSelectorOnMainThread:@selector(method) withObject:nilwaitUntilDone:YES];
[[NSThread mainThread] performSelector:@selector(method) withObject:nil];
4. RunLoop方法
[[NSRunLoop mainRunLoop] performSelector:@selector(method) withObject:nil];