SDWebImage内存策略

2020-04-09  本文已影响0人  cheng1314

## SDImageCache初始化的时候注册了三个通知

```

- (id)initWithNamespace:(NSString *)ns diskCacheDirectory:(NSString *)directory {

    if ((self = [super init])) {

        NSString *fullNamespace = [@"com.hackemist.SDWebImageCache." stringByAppendingString:ns];

        // initialise PNG signature data

        kPNGSignatureData = [NSData dataWithBytes:kPNGSignatureBytes length:8];

        // Create IO serial queue

        _ioQueue = dispatch_queue_create("com.hackemist.SDWebImageCache", DISPATCH_QUEUE_SERIAL);

        // Init default values

        _maxCacheAge = kDefaultCacheMaxCacheAge;

        // Init the memory cache

        _memCache = [[AutoPurgeCache alloc] init];

        _memCache.name = fullNamespace;

        // Init the disk cache

        if (directory != nil) {

            _diskCachePath = [directory stringByAppendingPathComponent:fullNamespace];

        } else {

            NSString *path = [self makeDiskCachePath:ns];

            _diskCachePath = path;

        }

        // Set decompression to YES

        _shouldDecompressImages = YES;

        // memory cache enabled

        _shouldCacheImagesInMemory = YES;

        // Disable iCloud

        _shouldDisableiCloud = YES;

        dispatch_sync(_ioQueue, ^{

            _fileManager = [NSFileManager new];

        });

#if TARGET_OS_IOS

        // Subscribe to app events

        [[NSNotificationCenter defaultCenter] addObserver:self

                                                selector:@selector(clearMemory)

                                                    name:UIApplicationDidReceiveMemoryWarningNotification

                                                  object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self

                                                selector:@selector(cleanDisk)

                                                    name:UIApplicationWillTerminateNotification

                                                  object:nil];

        [[NSNotificationCenter defaultCenter] addObserver:self

                                                selector:@selector(backgroundCleanDisk)

                                                    name:UIApplicationDidEnterBackgroundNotification

                                                  object:nil];

#endif

    }

    return self;

}

```

- 当收到系统内存不足警告的时候,会调用clearMemory方法,清除内存中所有的图片缓存。

- 当程序进入后台时,把任何未完成的工作都标记在你的位置上

直接停止或结束任务,调用cleanDiskWithCompletionBlock,过期的缓存文件全部删除,缓存总大小超过 maxSize时,从最大的文件开始删除直到当前缓存大小在 maxSize/2 值以下。执行完cleanDiskWithCompletionBlock之后有回调,结束后台任务。

- 当收到程序将要杀掉进程的时候,会对磁盘中的文件数据进行清理。和程序进入后台的回方法一样,调用cleanDiskWithCompletionBlock,无block回调。

上一篇 下一篇

猜你喜欢

热点阅读