- 使用Thread 的類方法
detachNewThreadSelector
創(chuàng)建線程
- (void)viewDidLoad
{
// 調(diào)用類方法的新線程 立即開始執(zhí)行
// [NSThread detachNewThreadSelector:@selector(doIt) toTarget:self withObject:nil];
NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
// 線程優(yōu)先級(jí)
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];
}
- 調(diào)用實(shí)例方法
start
- (void)viewDidLoad
{
// 調(diào)用類方法的新線程 立即開始執(zhí)行
NSThread *thd = [[NSThread alloc] initWithTarget:self selector:@selector(doIt) object:nil];
// 線程優(yōu)先級(jí)
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
{
//創(chuàng)建操作隊(duì)列
NSOperationQueue *operationQueue = [[NSOperationQueue alloc] init];
//設(shè)置隊(duì)列中最大的操作數(shù)
[operationQueue setMaxConcurrentOperationCount:1];
//創(chuàng)建操作(最后的object參數(shù)是傳遞給selector方法的參數(shù))
NSInvocationOperation *operation = [[NSInvocationOperation alloc] initWithTarget:self selector:@selector(doIt) object:nil];
//將操作添加到操作隊(duì)列
[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
子類
來創(chuàng)建線程
@implementation MyTaskOperation
//相當(dāng)于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];