Lazy loading of image in tableview

前端 未结 5 1927
被撕碎了的回忆
被撕碎了的回忆 2021-01-25 09:57

Im trying to load the image of my uitableviewcells in lazy mode.

I\'m trying to do it in the simplest possible way, I saw a lot of examples but they were going further t

5条回答
  •  醉酒成梦
    2021-01-25 10:29

    Using the 3rd party library source code would be easiest, but here's how you would do it in code. You are going to want to make a NSMutableArray either as a property in your .h or at the top of your .m like this:

    @implementation viewController{
         NSMutableArray *picList;
    }
    

    and in -initWithCoder: or, whatever init you are overloading:

    picList = [[NSMutableArray alloc] init]; 
    

    in – tableView:cellForRowAtIndexPath: (fullPicURL is the URL):

    if([self imageExists:fullPicURL]){
    
        shoePic = [picList objectForKey:fullSmallPicURL];   
    
    } else {
    
        NSURL *picURL = [NSURL URLWithString:fullPicURL];
    
        shoePic = [UIImage imageWithData:[NSData dataWithContentsOfURL:picURL]];
        NSDictionary *thisImage = [NSDictionary dictionaryWithObject:shoePic forKey:fullSmallPicURL];
        [cachedImages addEntriesFromDictionary:thisImage];
    } 
    

    where -imageExists: is a function you write which checks the dictionary for the url. The object is the picture itself, the key is the url. Then you do cell.image = showPic;, or whatever you want to call it, and you're done for cacheing. In order to load them asynchronously, do this:

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    
        NSData *data = [NSData dataWithContentsOfURL:shoes];
        [self performSelectorOnMainThread:@selector(fetchedShoeData:) withObject:data waitUntilDone:YES];
    
    });
    

    and at the end of fetchedData:

    [self.tableView reloadData];
    

    then just make sure you edit –numberOfSectionsInTableView: to change itself if it has to. Might be some other things you need to do to get it working 100%, let me know

提交回复
热议问题