iOS开发中的多线程

来源:互联网 发布:网络营销软件有哪些 编辑:程序博客网 时间:2024/06/11 20:47
  最近整理了一下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 { }```

0 0
原创粉丝点击