- 使用Thread 的类方法
detachNewThreadSelector
创建线程
- (void)viewDidLoad
{
// 调用类方法的新线程 立即开始执行
// [NSThread detachNewThreadSelector:@selector(doIt) toTarget:self withObject:nil];
NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
// 线程优先级
thd.threadPriority = 10;
[thd start];
}
-(void)doIt{
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgv];
}
- 调用实例方法
start
- (void)viewDidLoad
{
// 调用类方法的新线程 立即开始执行
NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
// 线程优先级
thd.threadPriority = 10;
[thd start];
}
-(void)doIt{
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgv];
}
NSOperationQueue
- (void)viewDidLoad
{
//创建操作队列
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//设置队列中最大的操作数
[operationQueue setMaxConcurrentOperationCount:1];
//创建操作(最后的object参数是传递给selector方法的参数)
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doIt) object:nil];
//将操作添加到操作队列
[operationQueue addOperation:operation];
}
-(void)doIt{
UIImage *img = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://pic14.nipic.com/20110522/7411759_164157418126_2.jpg"]]];
UIImageView *imgv = [[UIImageView alloc] initWithImage:img];
[self.view addSubview:imgv];
}
- 使用NSOperation
子类
来创建线程
@implementation MyTaskOperation
//相当于Java线程中的run方法
-(void)main
{
//do someting...
NSLog(@"Thread is running...");
[NSThreadsleepForTimeInterval:3];
NSLog(@"Thread is done...");
}
@end
使用方法
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
MyTaskOperation *myTask = [[MyTaskOperation alloc] init];
[operationQueue addOperation:myTask];
[myTask release];
[operationQueue release];