//虽然现在在多线程方面大多都在用GCD,当其他方式我们还是应该有所了解,给大家介绍一下NSThread和NSInvocationOperation的简单用法
@interface
yxpViewController ()
{
UIImageView *_imageView;
//声明一个队列
NSOperationQueue *_operationQueue;
}
@end
@implementation yxpViewController
- (void)viewDidLoad
{
[super
viewDidLoad];
//初始化操作队列
_operationQueue = [[NSOperationQueue
alloc]
init];
//在这里限定了该队列只同时运行一个线程
[_operationQueue
setMaxConcurrentOperationCount:1];
//初始化一_ImageView
_imageView=[[UIImageView
alloc] initWithFrame:CGRectMake(10,
70,
300, 450)];
_imageView.backgroundColor=[UIColor
grayColor];
_imageView.animationDuration=3.0;
_imageView.animationRepeatCount=0;
[self.view
addSubview:_imageView];
//下面两种方法添加一个线程
//创建一个NSInvocationOperation对象,并初始化到方法
//在这里,selector参数后的值是你想在另外一个线程中运行的方法(函数,Method)
//在这里,object后的值是想传递给前面方法的数据
NSInvocationOperation* theOp = [[NSInvocationOperation
alloc]
initWithTarget:self
selector:@selector(addTaskMethod:)
object:_imageView];
// Operation加入到队列中
[_operationQueue
addOperation:theOp];
//[NSThread detachNewThreadSelector:@selector(addTaskMethod:) toTarget:self withObject:nil];
}
// 运行另外一个线程的方法
- (void)addTaskMethod:(id)data
{
NSString *url1=@"http://h.hiphotos.baidu.com/image/w%3D230/sign=b2d5c289123853438ccf8022a311b01f/91ef76c6a7efce1b1ae9f92fad51f3deb58f6510.jpg";
NSString *url2=@"http://h.hiphotos.baidu.com/image/pic/item/d058ccbf6c81800aae834e8bb33533fa838b47d5.jpg";
NSString *url3=@"http://d.hiphotos.baidu.com/image/pic/item/f2deb48f8c5494eec3ba65132ff5e0fe99257e1b.jpg";
NSString *url4=@"http://g.hiphotos.baidu.com/image/pic/item/a6efce1b9d16fdfa81f4ace4b68f8c5494ee7b1b.jpg";
NSString *url5=@"http://g.hiphotos.baidu.com/image/pic/item/d6ca7bcb0a46f21f70031fdbf4246b600c33ae07.jpg";
NSArray *array=[[NSArray
alloc] initWithObjects:url1,url2,url3,url4,url5,
nil];
NSMutableArray *imageArray=[[NSMutableArray
alloc]
initWithCapacity:20];
for (NSString *string
in array) {
UIImage *image=[self
getImageFromURL:string];
[imageArray
addObject:image];
}
_imageView.animationImages=imageArray;
//回到主线程调用 在非线程中不能调用有关UI线程(主线程)的方法的,你可以直接调用一下看是否有效
[self
performSelectorOnMainThread:@selector(startImageViewAnimating)
withObject:nil
waitUntilDone:YES];
}
- (void)startImageViewAnimating
{
[_imageView
startAnimating];
}
//下载图片的方法
-(UIImage *) getImageFromURL:(NSString *)fileURL {
NSLog(@"执行图片下载函数");
UIImage * result;
NSData * data = [NSData
dataWithContentsOfURL:[NSURL
URLWithString:fileURL]];
result = [UIImage
imageWithData:data];
return result;
}
- (void)didReceiveMemoryWarning
{
[super
didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
@end
IOS多线程_NSThread和NSInvocationOperation