NSThread 有两种直接创建方式:
- (id)initWithTarget:(id)target selector:(SEL)selector object:(id)argument
+ (void)detachNewThreadSelector:(SEL)aSelector toTarget:(id)aTarget withObject:(id)anArgument
[NSThread detachNewThreadSelector:@selector(doSomething:) toTarget:self withObject:nil];
NSThread* myThread = [[NSThread alloc] initWithTarget:self
selector:@selector(doSomething:)
object:nil];
[myThread start];
//主线程
[self performSelectorOnMainThread:@selector(updateUI:) withObject:image waitUntilDone:YES];
GCD
//添加一个子线程
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
//读取文件
NSString *fileURL = [NSString stringWithFormat:@"http://cam.ppcam.tv/camera_image/2330000010/alarm.log"];
NSData *date = [NSData dataWithContentsOfURL:[NSURL URLWithString:fileURL]];
NSString* content = [[NSString alloc] initWithData:date encoding:NSASCIIStringEncoding];
//当子线程处理完成在主线程中处理
dispatch_sync(dispatch_get_main_queue(), ^{
m_labText.numberOfLines = 0;
m_labText.text = content;
self.m_strDataSource = content;
});
});
并行
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//1、get alarm info
[m_vcMain readAlarmInfo];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//2、get device cap
[CommonReq getDeviceCap];
});
dispatch_async(dispatch_get_global_queue(0, 0), ^{
//3、set bitstate to low and resolution to smooty
[CommonReq setCameraBitrate:@"0"]; //bitstate
[CommonReq switchLiveViewQuality:@"0"]; //Smooth
});
延迟执行
//延迟0.5秒执行
[self performSelector:@selector(clickloginBtn:) withObject:nil afterDelay:0.5];