IOS多线程编程NSThread的使用方法

2020-01-21 01:28:44于丽

bool isCancelThread = NO; 
- (void)stopClick 
{ 
 [NSObject cancelPreviousPerformRequestsWithTarget:self]; 
  
 if (self.thread) 
 { 
  BOOL isExecuting = [self.thread isExecuting]; 
  if (isExecuting) 
  { 
   NSLog(@"1 停止"); 
//   [self.thread cancel]; 
   isCancelThread = YES; 
  } 
 } 
} 

- (void)downloadImage:(NSString *)imageUrl 
{ 
 NSURL *url = [NSURL URLWithString:imageUrl]; 
 NSData *data = [[NSData alloc] initWithContentsOfURL:url]; 
 UIImage *image = [[UIImage alloc] initWithData:data]; 
 if (image == nil) 
 { 
   
 } 
 else 
 { 
//  [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES]; 
  [self performSelectorInBackground:@selector(updateImage:) withObject:image]; 
 } 
  
// NSURL *url = [NSURL URLWithString:imageUrl]; 
// NSURLRequest *request = [NSURLRequest requestWithURL:url]; 
// NSURLSession *session = [NSURLSession sharedSession]; 
// NSURLSessionDataTask *dataTask = [session dataTaskWithRequest:request completionHandler: ^(NSData *data, NSURLResponse *response, NSError *error) { 
//   
//  // 输出返回的状态码,请求成功的话为200 
//  NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response; 
//  NSInteger responseStatusCode = [httpResponse statusCode]; 
//  NSLog(@"%ld", responseStatusCode); 
//   
//  UIImage *image = [UIImage imageWithData:data]; 
////  [self performSelectorOnMainThread:@selector(updateImage:) withObject:image waitUntilDone:YES]; 
//  [self performSelectorInBackground:@selector(updateImage:) withObject:image]; 
// }]; 
//  
// // 使用resume方法启动任务 
// [dataTask resume]; 
} 

- (void)updateImage:(UIImage *)image 
{ 
 self.imageview.image = image; 
  
// self.imageview = [[UIImageView alloc] initWithFrame:CGRectMake(10.0, 10.0, (CGRectGetWidth(self.view.bounds) - 10.0 * 2), (CGRectGetWidth(self.view.bounds) - 10.0 * 2))]; 
// [self.view addSubview:self.imageview]; 
// self.imageview.backgroundColor = [UIColor colorWithWhite:0.5 alpha:0.2]; 
//  
// self.imageview.image = image; 
} 

NSString *imageUrl = @"http://www.easck.com/crop.0.0.1242.1242.1024/763fb12bjw8empveq3eq8j20yi0yiwhw.jpg"; 
// 隐藏创建 
// [self performSelectorInBackground:@selector(downloadImage:) withObject:imageUrl]; 
[self performSelectorOnMainThread:@selector(downloadImage:) withObject:imageUrl waitUntilDone:YES]; 
// 创建子线程-显示方法 
self.thread = [[NSThread alloc] initWithTarget:self selector:@selector(downloadImage:) object:imageUrl]; 
self.thread.name = @"imageDownload"; 
[self.thread start]; 

 

IOS,NSThread,多线程NSThread,NSThread的使用方法

如有疑问请留言或者到本站社区交流讨论,感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!