IOS多線程_NSThread和NSInvocationOperation – iPhone手機開發技術文章 iPhone軟體開發教學課程

//雖然現在在多線程方面大多都在用GCD,當其他方式我們還是應該有所瞭解,給大傢介紹一下NSThread和NSInvocationOperation的簡單用法

@interfaceyxpViewController ()

{

UIImageView *_imageView;

//聲明一個隊列

NSOperationQueue *_operationQueue;

}

@end

@implementation yxpViewController

– (void)viewDidLoad

{

[superviewDidLoad];

//初始化操作隊列

_operationQueue = [[NSOperationQueuealloc]
init];

//在這裡限定瞭該隊列隻同時運行一個線程

[_operationQueuesetMaxConcurrentOperationCount:1];

//初始化一_ImageView

_imageView=[[UIImageViewalloc]
initWithFrame:CGRectMake(10,70,
300,
450)];

_imageView.backgroundColor=[UIColorgrayColor];

_imageView.animationDuration=3.0;

_imageView.animationRepeatCount=0;

[self.viewaddSubview:_imageView];

//下面兩種方法添加一個線程

//第一種

//創建一個NSInvocationOperation對象,並初始化到方法

//在這裡,selector參數後的值是你想在另外一個線程中運行的方法(函數,Method)

//在這裡,object後的值是想傳遞給前面方法的數據

NSInvocationOperation* theOp = [[NSInvocationOperation
alloc] initWithTarget:self
selector:@selector(addTaskMethod:)
object:_imageView];

//當然也可以選擇直接調用start方法開始,不過這個樣做是同步的,也就是說還是要等後臺線程執行完成才執行主線程

//[theOp start];

// Operation加入到隊列中 是theOp和主線程同時執行,也就是異步線程,這樣才能達到我們的效果

[_operationQueue
addOperation:theOp];

//第二種

//用[NSThread detachNewThreadSelector:@selector(addTaskMethod:) toTarget:self withObject:nil]; 也可以增加一個線程 等效於上一種

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

}

// 運行另外一個線程的方法

– (void)addTaskMethod:(id)data

{

NSString *url1=@”/wp-content/images1/20181019/91ef76c6a7efce1b1ae9f92fad51f3deb58f6510144.gif”;

NSString *url2=@”/wp-content/images1/20181019/d058ccbf6c81800aae834e8bb33533fa838b47d5145.gif”;

NSString *url3=@”/wp-content/images1/20181019/f2deb48f8c5494eec3ba65132ff5e0fe99257e1b146.gif”;

NSString *url4=@”/wp-content/images1/20181019/a6efce1b9d16fdfa81f4ace4b68f8c5494ee7b1b147.gif”;

NSString *url5=@”/wp-content/images1/20181019/d6ca7bcb0a46f21f70031fdbf4246b600c33ae07148.gif”;

NSArray *array=[[NSArrayalloc]
initWithObjects:url1,url2,url3,url4,url5,nil];

NSMutableArray *imageArray=[[NSMutableArrayalloc]
initWithCapacity:20];

for (NSString *stringin array) {

UIImage *image=[selfgetImageFromURL:string];

[imageArrayaddObject:image];

}

_imageView.animationImages=imageArray;

//回到主線程調用 在非線程中不能調用有關UI線程(主線程)的方法的,你可以直接調用一下看是否有效

[selfperformSelectorOnMainThread:@selector(startImageViewAnimating)withObject:nilwaitUntilDone:YES];

}

– (void)startImageViewAnimating

{

[_imageView startAnimating];

}

//下載圖片的方法

-(UIImage *) getImageFromURL:(NSString *)fileURL {

NSLog(@”執行圖片下載函數”);

UIImage * result;

NSData * data = [NSDatadataWithContentsOfURL:[NSURLURLWithString:fileURL]];

result = [UIImageimageWithData:data];

return result;

}

– (void)didReceiveMemoryWarning

{

[superdidReceiveMemoryWarning];

// Dispose of any resources that can be recreated.

}

@end

發佈留言