Swift   发布时间:2022-04-30  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了swift – 使用大量UIImage时的内存问题大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我在一个阵列上存储了大约100个UI Image.我知道有一个内存使用问题最终导致应用程序崩溃,特别是在旧设备(iPhone 4s)上.在存储DocumentsDirectory上的所有UIImages的用户体验方面 – 不是一个选项(花费太长时间).所以我在虑“合并”这两种方法.等到我收到内存使用警告,停止将图像保存到我的阵列,然后开始存储在磁盘上.我找不到正确的方法来处理内存泄漏/警告/使用调用

override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        print("memory warning")
    }@H_197_8@ 
 

当我在真实设备上进行测试时,它只是崩溃 – 没有调用方法.有什么建议?

解决方法

尝试使用图像缓存库.
最受欢迎的比较是:
https://bpoplauschi.wordpress.com/2014/03/21/ios-image-caching-sdwebimage-vs-fastimage/

我的经验:SDWebImage最适合通常来自互联网的URL源图像,而Haneke适用于基于ID的图像,例如从视频生成缩略图.
两者都在CocoaPods中提供.

SDWebImage使用COreData sqlite DB进行URL缓存.它没有“手工制作”图像的方法,但在从REST下载互联网图像的REST应用程序中广泛流行.我刚刚在AppStore MyHairDressers应用程序中发布它. FastCache使用文件进行URL缓存.但它也喜欢SDWebImage不适合缓存“手工制作”图像.两者都非常适合通过URL下载的图像. Haneke不仅可以通过URL按自定义ID存储图像.但是像FastCache一样需要一些配置.以下是一些配置的代码

HNKCacheFormat *cacheFormatThumbnail = [[HNKCache sharedCache] formats][CACHE_FORMAT_THUMBNAIL];
        if (cacheFormatThumbnail == nil)
        {
            cacheFormatThumbnail = [[HNKCacheFormat alloc] initWithName:CACHE_FORMAT_THUMBNAIL];
            cacheFormatThumbnail.size = CGSizeMake(100.0f,56.0f);
            cacheFormatThumbnail.scaleMode = HNKScaleModeAspectFit;
            cacheFormatThumbnail.compressionQuality = 0.5f;
            cacheFormatThumbnail.diskCapacity = 10 * 1024 * 1024; // 10MB
            cacheFormatThumbnail.preloadPolicy = HNKPreloadPolicyLastSession;
            [[HNKCache sharedCache] registerFormat:cacheFormatThumbnail];
        }
        HNKCacheFormat *cacheFormatPhoto = [[HNKCache sharedCache] formats][CACHE_FORMAT_PHOTO];
        if (cacheFormatPhoto == nil)
        {
            cacheFormatPhoto = [[HNKCacheFormat alloc] initWithName:CACHE_FORMAT_PHOTO];
            CGFloat scale = [[UIScreen mainScreen] scale];
            cacheFormatPhoto.size = CGSizeMake(1280.0f * scale,720.0f * scalE);
            cacheFormatPhoto.scaleMode = HNKScaleModeAspectFit;
            cacheFormatPhoto.compressionQuality = 0.5f;
            cacheFormatPhoto.diskCapacity = 50 * 1024 * 1024; // 50MB
            cacheFormatPhoto.preloadPolicy = HNKPreloadPolicyNone;
            [[HNKCache sharedCache] registerFormat:cacheFormatPhoto];
        }@H_197_8@ 
 

这里是创建缓存图像的示例(TableViewCell包含带缩略图的CollectionView):

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowATindexPath:(NSIndexPath *)indexPath
{
    VideoCell *cell = (VideoCell *)[super tableView:tableView cellForRowATindexPath:indexPath];
    VideoAsset *asset = (VideoAsset *)[self.fetchedResultsController objectATindexPath:indexPath];
    if ([asset thumbnails] == 0)
    {
        MBProgressHUD *hud = [[MBProgressHUD alloc] initWithView:[cell thumbnails]];
        hud.removeFromSuperViewOnHide = YES;
        [[cell thumbnails] addSubview:hud];
        hud.labelText = NSLocalizedString(@"H11",nil);
        [hud show:YES];
        CGFloat scale = [[UIScreen mainScreen] scale];
        CGSize size = CGSizeMake(100.0f * scale,56.0f *scalE);
        __weak typeof(cell) weakCell = cell;
        [asset generateThumbnails:self->thumbnailsCount offset:self->thumbnailsOffset size:size completion:^(NSArray *thumbnails) {
            dispatch_async(dispatch_get_main_queue(),^{
                [hud hide:YES];
            });
            if ((thumbnails != nil) && ([thumbnails count] > 0))
            {
                HNKCache *cache = [HNKCache sharedCache];
                NSUInteger n = 0;
                NSUInteger keyHash = [[[asset assetURL] absoluteString] hash];
                for (UIImage *image in thumbnails)
                {
                    [cache setImage:image forKey:[NSString StringWithFormat:@"%lu@%i",(unsigned long)keyHash,(int)(n++)] formatName:CACHE_FORMAT_THUMBNAIL];
                    dispatch_async(dispatch_get_main_queue(),^{
                        if (weakCell != nil)
                        {
                            __strong typeof(cell) strongCell = weakCell;
                            [[strongCell thumbnails] reloadData];
                        }
                    });
formatName:CACHE_FORMAT_PHOTO];
                }
            }
        }];
    }
    return (UITableViewCell *)cell;
}@H_197_8@ 
 

和使用(表视图单元格中集合的集合视图单元格):

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemATindexPath:(NSIndexPath *)indexPath
{
    ThumbnailCell *cell = [collectionView dequeueReusableCellWithReusEIDentifier:cellIdentifier forIndexPath:indexPath];
    NSString *key = [NSString StringWithFormat:@"%lu@%i",(unsigned long)[[[(VideoAsset *)self->_SELEctedObject assetURL] absoluteString] hash],(int)[indexPath item]];
    [cell setKey:key];
    [cell setTag:[indexPath item]];
    __weak typeof(cell) weakCell = cell;
    [[HNKCache sharedCache] fetchImageForKey:key formatName:CACHE_FORMAT_THUMBNAIL success:^(UIImage *imagE) {
        [[weakCell image] setImage:image];
    } failure:^(NSError *error) {
        if ([[error domain] isEqualToString:HNKErrorDomain] && ([error code] == HNKErrorImageNotFound))
        {
            [[weakCell image] setImage:[UIImage imagenamed:@"movieplaceholder"]];
        }
        else [error reportError];
    }];
    return cell;
}@H_197_8@ 
 

大佬总结

以上是大佬教程为你收集整理的swift – 使用大量UIImage时的内存问题全部内容,希望文章能够帮你解决swift – 使用大量UIImage时的内存问题所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。