您的位置:首页 > 移动开发 > IOS开发

iOS开发中遇到的几种多线程

2015-02-12 16:01 113 查看
最近整理了一下iOS开发中常用的几种多线程

// 第一种方式


NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(mutableThread) object:@"test"]; [thread start];


// 第二种方式


[NSThread detachNewThreadSelector:@selector(mutableThread) toTarget:self withObject:nil];


// 第三种方式


[self performSelectorInBackground:@selector(mutableThread) withObject:nil];


// 第四种方式


NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
[operationQueue addOperationWithBlock:^{
// 多线程上执行的方法
}];


// 第五种方式

线程队列可以同时添加多个线程 可以设置优先级等

NSOperationQueue *threadQueue = [[NSOperationQueue alloc] init];
NSInvocationOperation *op1 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
NSInvocationOperation *op2 = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(mutableThread) object:nil];
[threadQueue addOperation:op1];
[threadQueue addOperation:op2];


// 第六种方式 GCD 这个性能最好 推荐使用这个

dispatch_queue_create("test", NULL);
dispatch_async(queue,  ^{
// 多线程
// 回到主线程执行
dispatch_sync(dispatch_get_main_queue(), ^{
这里写代码片// 主线程操作的代码
});
});
return YES;
}


// 多线程执行的方法

注意!这边需要有一个自动释放池

- (void)mutableThread {
@autoreleasepool {
[self performSelectorOnMainThread:@selector(mainThread) withObject:nil waitUntilDone:NO];
}
}


// 主线程

- (void)mianThread {
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: