iOS - LocalCache 本地数据缓存


1、自定义方式本地数据缓存

1.1 自定义缓存 1

  • 沙盒路径下的 Library/Caches 用来存放缓存文件,保存从网络下载的请求数据,后续仍然需要继续使用的文件,例如网络下载的离线数据,图片,视频文件等。该目录中的文件系统不会自动删除,可以做离线访问。它的存放时间比 tmp 下的长,但是不如 Library 下的其它目录。总的来说 Caches 目录下存放的数据不能是应用程序运行所必需的,但是能提高应用访问性能的。可写入应用支持文件,保存应用程序再次启动需要的信息。iTunes 不会对这个目录的内容进行备份。要求程序员必需提供一个完善的清除缓存目录的 "解决方案"。

  • Objective-C

    	// 写缓存
    
    		- (void)writeLocalCacheData:(NSData *)data withKey:(NSString *)key {
    
    			// 设置存储路径
    			NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] 
    			                                                                     stringByAppendingPathComponent:key];
    
    			// 判读缓存数据是否存在
    			if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        		
        			// 删除旧的缓存数据
        			[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    			}
    
    			// 存储新的缓存数据
    			[data writeToFile:cachesPath atomically:YES];
    		}
    
    	// 读缓存
    
     		- (NSData *)readLocalCacheDataWithKey:(NSString *)key {
    
    			NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] 
    			                                                                     stringByAppendingPathComponent:key];
    
    			// 判读缓存数据是否存在
    			if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        
        			// 读取缓存数据
        			return [NSData dataWithContentsOfFile:cachesPath];
    			}
    
    			return nil;
    		}
    
    	// 删缓存
    
    		- (void)deleteLocalCacheDataWithKey:(NSString *)key {
    
    			NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)[0] 
    			                                                                     stringByAppendingPathComponent:key];
    
    			// 判读缓存数据是否存在
    			if ([[NSFileManager defaultManager] fileExistsAtPath:cachesPath]) {
        
        			// 删除缓存数据
        			[[NSFileManager defaultManager] removeItemAtPath:cachesPath error:nil];
    			}
    		}
    
  • Swift

    	// 写缓存
          
        	func writeLocalCacheData(data:NSData, withKey key:String) {
    
    			// 设置存储路径
            	let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
            	                 .stringByAppendingString("/\(key)")
    
    			// 判读缓存数据是否存在
            	if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {
    
    				// 删除旧的缓存数据
                	try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)
            	}
    
    			// 存储新的缓存数据
            	data.writeToFile(cachesPath, atomically: true)
        	}
    		
    	// 读缓存
            
        	func readLocalCacheDataWithKey(key:String) -> NSData? {
    
            	let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
            	                 .stringByAppendingString("/\(key)")
    
    			// 判读缓存数据是否存在
            	if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {
    
    				// 读取缓存数据
                	return NSData(contentsOfFile: cachesPath)
            	}
    
            	return nil
        	}
            
    	// 删缓存
            
        	func deleteLocalCacheDataWithKey(key:String) {
    
            	let cachesPath = NSSearchPathForDirectoriesInDomains(.CachesDirectory, .UserDomainMask, true)[0]
            	                 .stringByAppendingString("/\(key)")
    
    			// 判读缓存数据是否存在
            	if NSFileManager.defaultManager().fileExistsAtPath(cachesPath) {
    
    				// 删除缓存数据
                	try! NSFileManager.defaultManager().removeItemAtPath(cachesPath)
            	}
        	}
    

1.2 自定义缓存 2

  • 沙盒路径下的 Library/Preferences 常用来放置配置文件、数据文件、模板等应用在运行中与用户相关,而又希望对用户不可见的文件,如系统偏好设置,用户偏好设置等文件。使用 NSUserDefaults 类进行偏好设置文件的创建、读取和修改。

  • Objective-C

    	// 写缓存
    
    		- (void)saveCacheData:(NSData *)data withType:(int)type andID:(int)_id {
                
        		NSUserDefaults *setting = [NSUserDefaults standardUserDefaults];
        		NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];
                
    			[setting setObject:data forKey:key];
    			[setting synchronize];
    		}
    
    	// 读缓存
    
    		- (NSData *)getCacheDataWithType:(int)type andID:(int)_id {
                
         		NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    			NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];
                
    			return [setting objectForKey:key];
    		}
    
    	// 删缓存
    
      		- (void)removeCacheDataWith:(int)type andID:(int)_id {
                
    			NSUserDefaults * setting = [NSUserDefaults standardUserDefaults];
    			NSString *key = [NSString stringWithFormat:@"detail-%d-%d", type, _id];
                
    			[setting removeObjectForKey:key];
    			[setting synchronize];
    		}
    
  • Swift

    	// 写缓存
            
    		func saveCacheData(data:NSData, withType type:Int, andID _id:Int) {
                
    			let setting = NSUserDefaults.standardUserDefaults()
    			let key = String(format: "detail-%d-%d", type, _id)
                
    			setting.setObject(data, forKey: key)
    			setting.synchronize()
    		}
            
    	// 读缓存
            
    		func getCacheDataWithType(type:Int, andID _id:Int) -> NSData? {
                
    			let setting = NSUserDefaults.standardUserDefaults()
    			let key = String(format: "detail-%d-%d", type, _id)
                
    			return setting.objectForKey(key) as? NSData
    		}
            
    	// 删缓存
            
    		func removeCacheDataWithType(type:Int, andID _id:Int) {
                
    			let setting = NSUserDefaults.standardUserDefaults()
    			let key = String(format: "detail-%d-%d", type, _id)
                
    			setting.removeObjectForKey(key)
    			setting.synchronize()
    		}	
    

2、EGOCache 方式本地数据缓存

  • EGOCache 一个简单、线程安全的基于 key-value 的缓存框架,原生支持 NSString、UI/NSImage、和 NSData,也支持储存任何实现 <NSCoding> 协议的类。
  • EGOCache 只有一个类,并且为单例类,只有 EGOCache.h 和 EGOCache.m 两个文件。
  • EGOCache 只提供了磁盘缓存,没有提供内存缓存,同时,也提供了清理缓存的方法。
  • EGOCache 可以设定缓存过期时间,默认是 1 天,过期的缓存在创建 EGOCache 对象时会被删除。

2.1 添加 EGOCache

  • Github 网址:https://github.com/enormego/EGOCache

  • EGOCache 使用 ARC

  • Objective-C

    	// 添加第三方库文件
    	EGOCache-2.1.3
    
    	// 包含头文件
    	#import "EGOCache.h"
    
  • Swift

    	// 添加第三方库文件
    	EGOCache-2.1.3
    
    	// 创建名为 “项目名-Bridging-Header.h” 的桥接头文件,如:
    	SwiftLocalCache-Bridging-Header.h
    
    	// 在 TARGETS -> Build Setting -> Swift Compiler - Code generation -> Objective-C Bridging Header 中
    	// 添加 “项目名/项目名-Bridging-Header.h” 路径,如:
    	SwiftLocalCache/SwiftLocalCache-Bridging-Header.h
    
    	// 在创建的桥接头文件中包含头文件
    	#import "EGOCache.h"
    

2.2 EGOCache 缓存

  • Objective-C

    	// 判断缓存数据是否存在
    
    		BOOL hasLocalCache = [[EGOCache globalCache] hasCacheForKey:@"qqCache"];
    		
    	// 读取缓存数据
        
    		NSData *localData = [[EGOCache globalCache] dataForKey:@"qqCache"];
        
    	// 存储缓存数据
                
    		[[EGOCache globalCache] setData:data forKey:@"qqCache"];
    
  • Swift

    	// 判断缓存数据是否存在
        
    		let hasLocalCache = EGOCache.globalCache().hasCacheForKey("qqCache")
        
    	// 读取缓存数据
            
    		let localData = EGOCache.globalCache().dataForKey("qqCache")
            
    	// 存储缓存数据
                    
    		EGOCache.globalCache().setData(data, forKey: "qqCache")
    

2.3 EGOCache 属性方法

  • 判断缓存数据是否存在方法

    	// 判断指定缓存的数据是否存在
    	- (BOOL)hasCacheForKey:(NSString* __nonnull)key;
    
  • 存储缓存数据方法

    	// 存储 NSData 型数据
    	- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key;
    	- (void)setData:(NSData* __nonnull)data forKey:(NSString* __nonnull)key 
    	                           withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
    	// 存储 NSString 型数据
    	- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key;
    	- (void)setString:(NSString* __nonnull)aString forKey:(NSString* __nonnull)key 
    	                                  withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
    	// 存储 UIImage 型数据
    	- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key;
    	- (void)setImage:(UIImage* __nonnull)anImage forKey:(NSString* __nonnull)key 
    	                                withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
    	// 存储 PList 型数据
    	- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key;
    	- (void)setPlist:(nonnull id)plistObject forKey:(NSString* __nonnull)key 
    	                            withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
    	// 存储 OBject 型数据
    	- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key;
    	- (void)setObject:(nonnull id<NSCoding>)anObject forKey:(NSString* __nonnull)key 
    	                                    withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
  • 读取缓存数据方法

    	// 读取 NSData 型缓存数据
    	- (NSData* __nullable)dataForKey:(NSString* __nonnull)key;
    
    	// 读取 NSString 型缓存数据
    	- (NSString* __nullable)stringForKey:(NSString* __nonnull)key;
    
    	// 读取 UIImage 型缓存数据
    	- (UIImage* __nullable)imageForKey:(NSString* __nonnull)key;
    
    	// 读取 PList 型缓存数据
    	- (NSData* __nullable)plistForKey:(NSString* __nonnull)key;
    
    	// 读取 OBject 型缓存数据
    	- (nullable id<NSCoding>)objectForKey:(NSString* __nonnull)key;
    
  • 复制缓存数据方法

    	// 复制指定缓存数据	
    	- (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key;
    	
    	- (void)copyFilePath:(NSString* __nonnull)filePath asKey:(NSString* __nonnull)key 
    	                                     withTimeoutInterval:(NSTimeInterval)timeoutInterval;
    
  • 清除缓存数据方法

    	// 清除全部缓存数据
    	- (void)clearCache;
    
    	// 清除指定缓存的数据
    	- (void)removeCacheForKey:(NSString* __nonnull)key;
    
  • 读取缓存信息方法

    	// 获取指定缓存的缓存时间
    	- (NSDate* __nullable)dateForKey:(NSString* __nonnull)key;
    
    	// 获取所有缓存的 key 值
    	- (NSArray* __nonnull)allKeys;
    
  • 创建缓存对象方法

    	// 这种方法创建的缓存对象不是单例类,可以自己设置缓存路径
    	- (nonnull instancetype)initWithCacheDirectory:(NSString* __nonnull)cacheDirectory;
    
  • 缓存时间属性

    	// Default is 1 day
    	@property(nonatomic) NSTimeInterval defaultTimeoutInterval;
    


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM