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

iOS线程-NSOperation,NSThread以及GCD

2014-01-03 17:31 316 查看
iOS开发中实现多线程有三种方式:NSThread,NSOperation和GCD。本文介绍三种方式的具体实现。

1.NSThread

初始化一个线程有两种方式:

/*******NSObject的类方法**************/
[self performSelectorInBackground:@selector(secondMethod) withObject:self];

/*******NSThread,有两种方法**********/
//1.类方法 会自动运行main方法
[NSThread detachNewThreadSelector:@selector(firstMethod) toTarget:self withObject:nil];
//2.alloc 线程需要start
NSThread *thread = [[NSThread alloc] initWithTarget:self selector:@selector(firstMethod) object:nil];
[thread start];


2.NSOperation

NSOperationQueue *queue = [[NSOperationQueue alloc] init];
queue.maxConcurrentOperationCount = 3;//最多同时运行的线程数
for (int i=0; i<10; i++) {
MyOperation *opr = [[MyOperation alloc] init];//自定义一个operation类,继承自NSOperation
opr.time = i;
[queue addOperation:opr];
[opr release];
}
  MyOperation.h

#import <Foundation/Foundation.h>

@interface MyOperation : NSOperation
@property (nonatomic, assign) int time;
@end


 MyOperation.m

#import "MyOperation.h"

@implementation MyOperation
@synthesize time;

//只要实例化该对象并添加到队列中之后,会自动调用main方法
- (void)main
{
sleep(self.time);
NSLog(@"%d", self.time);
}
@end


3. GCD

关于GCD会用另一篇文章介绍,此处直接写用法

//创建一个串行线程队列,第一个参数是队列的名字,第二个参数不知道
dispatch_queue_t opqueue = dispatch_queue_create("my operation queue", NULL);
//异步执行线程,在t中执行block语句
dispatch_async(opqueue, ^{
[self first];
});

//得到一个并行线程队列,第一个参数是优先级
dispatch_queue_t opqueue2 = dispatch_get_global_queue(0, 0);
dispatch_async(opqueue2, ^{
[self second];
});


另外,这些线程不能操作UI,但是可以回调,让来执行UI方面的操作,有两种方式:

//回到主线程
//第一种方法
// [self performSelectorOnMainThread:@selector(first) withObject:self waitUntilDone:NO];
//第二种方法
dispatch_async(dispatch_get_main_queue(), ^{
_imageView.image = img;
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐