iOS - 归档存储数据

利用归档存储数据

====== 缓存数据======
/**  
 @param object 数据
 @param key    key值
 */
+ (void) cacheObject:(id)object forKey:(NSString *)key {

    [[NSUserDefaults standardUserDefaults] setObject:object forKey:key];
}
====== 获取缓存数据 ======
 /**
  @param key key值
  @return 缓存的数据
    */
+ (id) objectInCacheForKey:(NSString *)key{

    return [[NSUserDefaults standardUserDefaults] objectForKey:key];
}
====== 缓存BOOL ======
/**
 @param bol YES/NO
 @param key key值
  */
+ (void) cacheBool:(BOOL)bol forKey:(NSString *)key {

    [[NSUserDefaults standardUserDefaults] setBool:bol forKey:key];
}
====== 获取缓存的BOOL值 ======
/**
  @param key key值
  @return YES/NO
   */ 
+ (BOOL) boolInCacheForKey:(NSString *)key {

    return [[NSUserDefaults standardUserDefaults] boolForKey:key];
}
====== 归档,以文件形式存储数据 ======
/**
  @param object   数据
  @param fileName 文件名
  */
+(void)archiveRootObject:(id)object toFile:(NSString *)fileName {

    NSString *filePath = [self filePath:fileName];

    [NSKeyedArchiver archiveRootObject:object toFile:filePath];

}
====== 解档,获取文件内容 ======
/**
  @param fileName 文件名
  @return 存储在文件中的内容
  */
+ (id) unarchiveObjectWithFile:(NSString *)fileName {
    
    NSString *filePath = [self filePath:fileName];

    return [NSKeyedUnarchiver unarchiveObjectWithFile:filePath];
}
====== 获取文件路径 ======
/**
 @param fileName 文件名
 @return 文件路径
  */
+ (NSString * ) filePath:(NSString *)fileName {

    return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:fileName];
}
====== 判断文件是否存在 ======
/**  
  @param fileName 文件名
 @return YES/NO
  */
+  (BOOL)  cacheFileExistsAtPath:(NSString *)fileName {

    BOOL isExist = NO;

    NSFileManager *fileManager = [NSFileManager defaultManager];

    if ([fileManager fileExistsAtPath:[self filePath:fileName]]) {
    
        isExist = YES;
    
    }  else {
    
        isExist = NO;
    }

    return isExist;
}
====== 删除路径下指定文件名的文件 ======
/**
  @param fileName 文件名
  */
+ (void) removeCacheFileAtPath:(NSString *)fileName {

    if ([YDArchiveCacheManager cacheFileExistsAtPath:fileName]) {
    
        NSFileManager *fileManager = [NSFileManager defaultManager];
    
        NSError *err;
    
        [fileManager removeItemAtPath:[self filePath:fileName] error:&err];
    
    }
}

你可能感兴趣的:(iOS - 归档存储数据)