SoFunction
Updated on 2025-04-03

iOS multi-threading implementation of multi-picture download function

This example shares the specific code for iOS multi-threading multi-picture download function for your reference. The specific content is as follows

1. The model file code is as follows

//  
 
#import <Foundation/> 
 
@interface XMGAPP : NSObject 
 
/** Name of APP */ 
@property (nonatomic, strong) NSString *name; 
/** The URL address of the APP picture */ 
@property (nonatomic, strong) NSString *icon; 
/** APP downloads */ 
@property (nonatomic, strong) NSString *download; 
 
+(instancetype)appWithDict:(NSDictionary *)dict; 
@end 
//  
 
#import "" 
 
@implementation XMGAPP 
 
+(instancetype)appWithDict:(NSDictionary *)dict 
{ 
  XMGAPP *appM = [[XMGAPP alloc]init]; 
  //KVC 
  [appM setValuesForKeysWithDictionary:dict]; 
   
  return appM; 
} 
@end 

The controller.m code is as follows:

//  
 
#import "" 
#import "" 
 
@interface ViewController () 
/** tableView's data source */ 
@property (nonatomic, strong) NSArray *apps; 
/** Memory cache */ 
@property (nonatomic, strong) NSMutableDictionary *images; 
/** Queue */ 
@property (nonatomic, strong) NSOperationQueue *queue; 
/** Operation cache */ 
@property (nonatomic, strong) NSMutableDictionary *operations; 
@end 
 
@implementation ViewController 
 
#pragma mark ---------------------- 
#pragma mark lazy loading 
-(NSOperationQueue *)queue 
{ 
  if (_queue == nil) { 
    _queue = [[NSOperationQueue alloc]init]; 
    //Set the maximum number of concurrency    _queue.maxConcurrentOperationCount = 5; 
  } 
  return _queue; 
} 
-(NSMutableDictionary *)images 
{ 
  if (_images == nil) { 
    _images = [NSMutableDictionary dictionary]; 
  } 
  return _images; 
} 
-(NSArray *)apps 
{ 
  if (_apps == nil) { 
     
    //Dictionary array    NSArray *arrayM = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"" ofType:nil]]; 
     
    //Dictionary array---->Model array    NSMutableArray *arrM = [NSMutableArray array]; 
    for (NSDictionary *dict in arrayM) { 
      [arrM addObject:[XMGAPP appWithDict:dict]]; 
    } 
    _apps = arrM; 
  } 
  return _apps; 
} 
 
-(NSMutableDictionary *)operations 
{ 
  if (_operations == nil) { 
    _operations = [NSMutableDictionary dictionary]; 
  } 
  return _operations; 
} 
 
#pragma mark ---------------------- 
#pragma mark UITableViewDatasource 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
  return 1; 
} 
 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
  return ; 
} 
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
  static NSString *ID = @"app"; 
   
  //1.Create cell  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; 
   
  //2. Set cell data  //2.1 Get the corresponding data of the cell in this bank  XMGAPP *appM = []; 
   
  //2.2 Set the title   = ; 
   
  //2.3 Set subtitles   = ; 
   
  //2.4 Set icons   
  //First check the image in the memory cache when it already exists. If it exists for so long, it will be used directly, otherwise check the disk cache  //If there is disk cache, save a copy to memory and set the picture, otherwise download it directly  //1) No downloads  //2) Reopen the program   
  UIImage *image = [ objectForKey:]; 
  if (image) { 
     = image; 
    NSLog(@"The image at %zd uses the image in the memory cache",) ; 
  }else 
  { 
    //Save the picture to the sandbox cache    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
    // Obtain the name of the image, cannot include/    NSString *fileName = [ lastPathComponent]; 
    //The full path of the stitching image    NSString *fullPath = [caches stringByAppendingPathComponent:fileName]; 
     
     
    //Check disk cache    NSData *imageData = [NSData dataWithContentsOfFile:fullPath]; 
    //abolition    imageData = nil; 
     
    if (imageData) { 
      UIImage *image = [UIImage imageWithData:imageData]; 
       = image; 
       
      NSLog(@"The image at %zd uses the image in the disk cache",) ; 
      //Save the image to memory cache      [ setObject:image forKey:]; 
       
//      NSLog(@"%@",fullPath); 
    }else 
    { 
      //Check the image while downloading. If it takes so long, capture everything, otherwise add the download task.      NSBlockOperation *download = [ objectForKey:]; 
      if (download) { 
         
      }else 
      { 
         
        //Clear the original picture of the cell first         = [UIImage imageNamed:@"Snip20160221_306"]; 
         
        download = [NSBlockOperation blockOperationWithBlock:^{ 
          NSURL *url = [NSURL URLWithString:]; 
          NSData *imageData = [NSData dataWithContentsOfURL:url]; 
          UIImage *image = [UIImage imageWithData:imageData]; 
           
           NSLog(@"%zd--Download---",); 
           
          //Fault-tolerant processing          if (image == nil) { 
            [ removeObjectForKey:]; 
            return ; 
          } 
          //Demonstrate the slow internet speed          //[NSThread sleepForTimeInterval:3.0]; 
         
          //Save the image to memory cache          [ setObject:image forKey:]; 
           
          //NSLog(@"Download---%@",[NSThread currentThread]); 
          //Communication between threads          [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
             
            // = image; 
            //Refresh a line            [ reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 
            //NSLog(@"UI---%@",[NSThread currentThread]); 
          }]; 
           
           
          //Write data to the sandbox          [imageData writeToFile:fullPath atomically:YES]; 
           
          //Download operation of removing pictures          [ removeObjectForKey:]; 
           
        }]; 
         
        //Add an operation to the operation cache        [ setObject:download forKey:]; 
         
        //Add operation to queue        [ addOperation:download]; 
      } 
       
    } 
  } 
   
  //3. Return cell  return cell; 
} 
 
-(void)didReceiveMemoryWarning 
{ 
  [ removeAllObjects]; 
   
  //Cancel all operations in the queue  [ cancelAllOperations]; 
} 
 
//It's very unsmooth ---> Open the child thread to download pictures//2. Repeat image download ---> Save the previously downloaded images first (Dictionary)//Memory Cache---->Disk Cache 
//3. The picture will not be refreshed --->Refresh a certain line//4. Repeat image download (Image download takes time, and the image must be displayed again before the image is fully downloaded)//5. Data confusion ---Set the placeholder picture 
/*
  Documents: Will backup, not allowed
  Libray
   Preferences: Preferences Save Account
   caches: cache files
  tmp: Temporary path (can be deleted at any time)
  */ 
 
@end 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.